CDECK  ID>,  MAIN. 
      PROGRAM SNANA
c
c Main snana program.
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER   IERR, IVERS, NFIT_PER_SN, JDIFF

c funtions



      EXTERNAL PRINT_CPUTIME

C ------------------- BEGIN -------------------

      JTIME_START = TIME()

      CALL PARSE_SNANA_ARGS()

      ISTAGE_SNANA = 0

c init some variables
      CALL INIT_SNVAR()

      CALL WARN_OLDINPUTS("init"//char(0), 0);

c read namelist
      CALL RDSNNML(IERR)
        IF ( IERR .NE. 0 ) GOTO 666

      ISTAGE_SNANA = ISTAGE_INIT

c check for dump flags (call to C code)
      CALL INIT_SNANA_DUMP(DUMP_STRING//char(0) )

c check if format is FITS or ASCII (set logicals  FORMAT_FITS[TEXT])
      CALL CHECK_FORMAT()

c ------------------------------------------------
c            Misc. inits for options

c check for CID list from &SNLCINP and/or separate file
      CALL INIT_SNCID_LISTS() ! Jun 2021

c check for SN,MJD list from file ... used for interpolation
      CALL RDFILE_SNMJDLIST()

c read optional tags
      CALL RDFILE_USERTAGS()

c init multi-season analysis
      CALL MULTISEASON(IFLAG_INI)  ! 1 = init flag

c check reformat options
      CALL INIT_REFORMAT(1)

c -----------------------------------------------
c prepare reading data; determine FITS or TEXT; read global info ...
      CALL INIT_READ_DATA()

c check reformat options
      CALL INIT_REFORMAT(2)

c continue with initialization that may depend on SURVEY and FILTERS.

c process namelist strings after we know
c the filters and survey
      CALL PROCSNNML(IERR)
        IF ( IERR .NE. 0 ) GOTO 666

      CALL INIT_FUDGE_FLUXCAL(IERR) ! fudge fluxes and/or errors
        IF ( IERR .NE. 0 ) GOTO 666

c intialize cutmask after reading data
      CALL INIT_CUTMASK(IERR)
        IF ( IERR .NE. 0 ) GOTO 666

c init early-LC selection
      CALL PARSE_EARLYLC_STRING()

c init REQUIRE_EPOCHS (Sep 2017)
      CALL PARSE_REQUIRE_EPOCHS_STRING()

c init cut-names now that we have the filter names
      CALL INIT_CUTNAMES(IERR)
        IF ( IERR .NE. 0 ) GOTO 666

      CALL READ_CALIB_WRAPPER(IERR)
        IF ( IERR .NE. 0 ) GOTO 666

c option to create SIMLIB from data (call after RDKCOR, Feb 2017)
      CALL MAKE_SIMLIB_FILE(1)

c check for valid MW GALextinct option  and print message
      CALL INIT_GALextinct()

      ISTAGE_SNANA = ISTAGE_RDSN

c parse SNTABLE_LIST string to know what tables & LCPLOTs to make
      CALL INIT_SNTABLE_OPTIONS()

c --------------------------------------------
c init output file; set OPTFIT based on program.
      NFIT_PER_SN = 1  ! only 1 fit per SN
      ISJOB_SNFIT = .TRUE.
      CALL MNDUMMY()   ! just to require minuit library.

      CALL INIT_OUTFILES(NFIT_PER_SN)

c Mar 2013, create subdir for monitor-init (CDTOPDIR below)
      CALL MAKEDIR_OUTPUT("MONINIT"//char(0), -1, 7 )

c --------------------------------------------
c plot a few Hubble diagrams for references
      IF ( USE_TABLEFILE )  CALL MON_HUBBLEREF ( IERR )

c initialize fitter before SN are selected
      CALL PRBANNER ( "CALL FITPAR_INI" )
      CALL FITPAR_INI ( IERR )
         IF ( IERR .NE. 0 ) GOTO 666

      CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! climb out of MONINIT subdir (Mar 2013)


c -------------------------------------------------
c Let user initialize their stuff before SN are selected
c Aug 14 2014: move after CDTOPDIR call.

      CALL PRBANNER ( "CALL USRINI" )
      CALL USRINI ( IERR )
         IF ( IERR .NE. 0 ) GOTO 666

c check command-line args after all inits
      CALL CHECK_LINE_ARGS()

c pak global survey info after all initialization (Mar 24 2013)
      IF ( USE_TABLEFILE .and. NFIT_PER_SN>0 ) CALL SNLCPAK_SURVEY()




c ######################################################
c
c   Read and process SN data : USRANA and MINUIT FIT
c
c ######################################################


c ------------------------------
      JTIME_LOOPSTART = TIME()
      JDIFF = JTIME_LOOPSTART - JTIME_START

      CALL PRINT_CPUTIME(JTIME_START, "CPUTIME_INIT"//char(0),
     &            "second"//char(0), 0, 20,20)

      call flush(6)
c ------------------------------

      DO ivers = 1, N_VERSION
         CALL PROCESS_DATA_VERSION(IVERS)
      ENDDO

c ------------------------------
      JTIME_LOOPEND = TIME()
c ------------------------------

       CALL SNANA_END()

c ###################
c  graceful end here
      CALL EXIT(0)
c ###################


c abort-end here

666   CONTINUE
      c1err = 'Fatal error in MAIN'
      CALL MADABORT("MAIN", c1err, "Check what gaver abort.")

      CALL EXIT(0)

      END  ! end MAIN program

C ==========================================

CDECK  ID>,  INIT_READ_DATA. 
      SUBROUTINE INIT_READ_DATA()

c Created Feb 2021
c Initialization driver for reading data files.
c Called once during global init stage.

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IVERS, INIT_NUM

C ------------ BEGIN -----------

c one-time init for both FITS and TEXT (since we don't know format yet)
      INIT_NUM = 0

      INIT_NUM = INIT_NUM+1
      CALL RD_SNFITSIO_INIT(INIT_NUM)

      INIT_NUM = INIT_NUM+1
      CALL RD_SNTEXTIO_INIT(INIT_NUM)

c set flag to read header of 1st light curve to get global info
c (SURVEY, FILTERS ..) needed for initialization

      IVERS = 1

      CALL GETINFO_PHOTOMETRY(IVERS)

      CALL EXEC_READ_DATA(IVERS,OPTMASK_SNDATA_GLOBAL)

      RETURN
      END    ! end INIT_READ_DATA

C ===============================
CDECK  ID>,  INIT_READ_OVERRIDE. 
      SUBROUTINE INIT_READ_OVERRIDE()

c Created May 2023
c Wrapper to call C-function RD_OVERRIDE_INIT
c
c Oct 2023: pass REQ_DOC=1 to require DOCANA.
c

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      INTEGER LENF_DATA, LENF_SIM, LEN_PRIV, REQ_DOC
      CHARACTER STR_TMP*(10*MXCHAR_FILENAME)

C ------------ BEGIN -----------

      CALL ENVreplace(HEADER_OVERRIDE_FILE)
      CALL ENVreplace(SIM_HEADER_OVERRIDE_FILE)

      LENF_DATA = INDEX(HEADER_OVERRIDE_FILE,' ') - 1
      LENF_SIM  = INDEX(SIM_HEADER_OVERRIDE_FILE,' ') - 1
      IF ( LENF_DATA > 0 .AND. LSIM_SNANA ) THEN
          print*,' '
          print*,' !=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!='
          print*,'    WARNING: HEADER_OVERRIDE_FILE ignored for sim'
          print*,' !=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!='
          print*,' '
      ENDIF

      REQ_DOC = 1  ! require DOCANA

      IF ( LENF_DATA > 0 ) THEN
       STR_TMP = HEADER_OVERRIDE_FILE(1:LENF_DATA)//char(0)
       CALL RD_OVERRIDE_INIT(STR_TMP, REQ_DOC, LENF_DATA)
      ENDIF
      IF ( LENF_SIM > 0 ) THEN
        STR_TMP = SIM_HEADER_OVERRIDE_FILE(1:LENF_SIM)//char(0)
        CALL RD_OVERRIDE_INIT(STR_TMP, REQ_DOC, LENF_SIM)
      ENDIF

      LEN_PRIV = INDEX(PRIVATE_VARNAME_READLIST,' ') -1
      IF ( LEN_PRIV > 0 ) THEN
         STR_TMP = PRIVATE_VARNAME_READLIST(1:LEN_PRIV)//char(0)
         CALL RD_PRIVATE_INIT(STR_TMP, REQ_DOC, LEN_PRIV) ! Sep 2023
      ENDIF

      RETURN
      END   ! end INIT_READ_OVERRIDE

C ==============================================
CDECK  ID>,  PREP_VERSION_SUBFOLDER. 
      SUBROUTINE PREP_VERSION_SUBFOLDER()

c Created Apr 7 2021
c If VERSION_PHOTOMETRY includes a sub-folder, e.g.,
c     'JLA2014/JLA2014_CSP'
c then reset VERSION_PHOTOMTRY = 'JLA2014_CSP' and update
c PRIVATE_DATA_PATH to be
c      SNDATA_ROOT/JLA2014          ! if input path is ''
c      [PRIVATE_DATA_PATH]/JLA2014  ! if input path is not ''
c
c Constraints
c   - multiple versions must be under same folder
c   - more than one slash in VERSION_PHOTOMETRY -> abort
c   - $ in VERSION_PHOTOMETRY -> abort (no ENVs)
c
c -------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER iver, jslash, LENV, LENP
      CHARACTER
     &   VERSION_ORIG*(MXCHAR_VERSION)
     &  ,VERSION*(MXCHAR_VERSION)
     &  ,FOLDER*(MXCHAR_VERSION)

C ------------- BEGIN ------------

      DO iver = 1, N_VERSION
         VERSION_ORIG = VERSION_PHOTOMETRY(iver)
         jslash  = INDEX(VERSION_ORIG,'/')
         LENV    = INDEX(VERSION_ORIG,' ') - 1
         IF ( jslash > 0 ) THEN
            folder  = VERSION_ORIG(1:jslash-1)
            VERSION = VERSION_ORIG(jslash+1:LENV)
             VERSION_PHOTOMETRY(iver) = VERSION
             IF ( PRIVATE_DATA_PATH == ' ' ) THEN
               LENP = INDEX(SNDATA_ROOT,' ') - 1
               PRIVATE_DATA_PATH = SNDATA_ROOT(1:LENP)
     &              // '/lcmerge/' // folder
             ELSE
               LENP = INDEX(PRIVATE_DATA_PATH,' ') - 1
               PRIVATE_DATA_PATH = PRIVATE_DATA_PATH(1:LENP)
     &              // '/' // folder
             ENDIF

c xxxxxxxxx
c            print*,' xxx -------------------------------------- '
c            print*,' xxx VERSION_ORIG = ', VERSION_ORIG(1:40)
c            print*,' xxx --> VERSION  = ', VERSION(1:40)
c            print*,' xxx --> PATH = ', PRIVATE_DATA_PATH(1:80)
c xxxxxxxxx

         ENDIF
      ENDDO

      RETURN
      END  ! end PREP_VERSION_SUBFOLDER


C ===========================================
CDECK  ID>,  READ_CALIB_WRAPPER. 
      SUBROUTINE READ_CALIB_WRAPPER(IERR)
c
c Ceated Nov 2022
c Wrapper subroutine to check if kcor/calib file is defined,
c and to call read-kcor function with appropriate args.
c [uses refactored C code]

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IERR  ! (O) return non-zero on error
      LOGICAL IGNOREFILE_fortran, USE_KCOR

      INTEGER LENF, OPT_FRAME, IFILT, IFILTDEF_OBS, IFILTDEF_REST
      CHARACTER*(MXCHAR_FILENAME) cKCOR_FILE, cFILTERS

      REAL*8
     &   D_MAGOBS_SHIFT_PRIM(MXFILT_ALL)
     &  ,D_MAGREST_SHIFT_PRIM(MXFILT_ALL)
     &  ,LAMAVG, LAMRMS, LAMMIN, LAMMAX, ZPOFF, MAG_PRIM

c external C codes
      REAL*8  GET_CALIB_ZPOFF_FILE, GET_CALIB_PRIMARY_MAG

      EXTERNAL
     &    FLOAT2DOUBLE
     &   ,READ_CALIB_DRIVER
     &   ,GET_CALIB_FILTINDEX_MAP
     &   ,GET_CALIB_FILTLAM_STATS
     &   ,GET_CALIB_ZPOFF_FILE
     &   ,GET_CALIB_PRIMARY_MAG
     &   ,GET_CALIB_NFILTDEF
     &   ,EXIST_CALIB_BXFILT
     &   ,GET_KCOR_ZRANGE

c ---------- BEGIN ---------

      IERR = 0

      EXIST_KCOR_FILE = .NOT. IGNOREFILE_fortran(KCOR_FILE)

      if ( .NOT. EXIST_KCOR_FILE ) RETURN

      USE_KCOR = .false.
      USE_KCOR = .true.


c prep arguments ...

      CALL ENVreplace(KCOR_FILE)  ! Mar 2016

      LENF = INDEX(KCOR_FILE,' ') - 1
      cKCOR_FILE = KCOR_FILE(1:LENF) // char(0)
      cFILTERS   = SURVEY_FILTERS(1:NFILTDEF_SURVEY) // char(0)

c convert primary mag-shifts from sngl to double precision
      CALL FLOAT2DOUBLE(MXFILT_ALL, MAGREST_SHIFT_PRIMARY_FILT,
     &           D_MAGREST_SHIFT_PRIM )  ! <== returned
      CALL FLOAT2DOUBLE(MXFILT_ALL, MAGOBS_SHIFT_PRIMARY_FILT,
     &           D_MAGOBS_SHIFT_PRIM )  ! <== returned


c @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

c read kcor file and store information (C code)

      CALL READ_CALIB_DRIVER(cKCOR_FILE, cFILTERS, USE_KCOR,
     &           D_MAGREST_SHIFT_PRIM, D_MAGOBS_SHIFT_PRIM)

c @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

c check for option to update filter trans for each SN
      CALL FILTER_UPDATE_INIT(IERR)

c - - - - - - -  - -
c load filter information from C struct to fortran common blocks

c OBS frame map is already loaded; get rest-frame map
      OPT_FRAME = OPT_FILTREST - 1
      CALL GET_CALIB_FILTINDEX_MAP(OPT_FRAME, NFILTDEF_REST,
     &        IFILTDEF_MAP_REST, IFILTDEF_INVMAP_REST)

c fetch wavelength stats per band: AVG, RMS, MIN, MAX
      OPT_FRAME = OPT_FILTOBS - 1
      DO ifilt = 1, NFILTDEF_SURVEY
         ifiltdef_obs = IFILTDEF_MAP_SURVEY(ifilt)
         LFILTDEF_OBS(ifiltdef_obs) = .TRUE.

         CALL GET_CALIB_FILTLAM_STATS(OPT_FRAME, IFILTDEF_OBS,
     &       LAMAVG, LAMRMS, LAMMIN, LAMMAX)
         FILTOBS_LAMAVG(ifiltdef_obs)     = sngl(LAMAVG)
         FILTOBS_LAMRMS(ifiltdef_obs)     = sngl(LAMRMS)
         FILTOBS_LAMRANGE(1,ifiltdef_obs) = sngl(LAMMIN)
         FILTOBS_LAMRANGE(2,ifiltdef_obs) = sngl(LAMMAX)

c     store primary mags
         MAG_PRIM = GET_CALIB_PRIMARY_MAG(OPT_FRAME,IFILTDEF_OBS)
         FILTOBS_MAG_PRIMARY(IFILTDEF_OBS) = MAG_PRIM

c       fetch ZPOFF from ZPOFF.DAT file in filter dir
         ZPOFF = GET_CALIB_ZPOFF_FILE(OPT_FRAME,ifiltdef_obs)
         FILTOBS_ZPOFF_SNPHOT(ifiltdef_obs) = sngl(ZPOFF)
      ENDDO

      OPT_FRAME = OPT_FILTREST - 1
      DO ifilt = 1, NFILTDEF_REST
         ifiltdef_rest = IFILTDEF_MAP_REST(ifilt)
         LFILTDEF_REST(ifiltdef_rest) = .TRUE.
         CALL GET_CALIB_FILTLAM_STATS(OPT_FRAME, IFILTDEF_REST,
     &       LAMAVG, LAMRMS, LAMMIN, LAMMAX)
         FILTREST_LAMAVG(ifiltdef_rest)     = sngl(LAMAVG)
         FILTREST_LAMRMS(ifiltdef_rest)     = sngl(LAMRMS)
         FILTREST_LAMRANGE(1,ifiltdef_rest) = sngl(LAMMIN)
         FILTREST_LAMRANGE(2,ifiltdef_rest) = sngl(LAMMAX)

c     store primary mags
         MAG_PRIM = GET_CALIB_PRIMARY_MAG(OPT_FRAME,IFILTDEF_REST)
         FILTREST_MAG_PRIMARY(IFILTDEF_REST) = MAG_PRIM
      ENDDO

c misc tasks to store info

      CALL SET_ZPOFF()

c store number of obs-frame and rest-frame filters
      CALL GET_CALIB_NFILTDEF(NFILTDEF_OBS,NFILTDEF_REST)

c check if BX filter is defined for OBS and REST fram
      CALL EXIST_CALIB_BXFILT(EXIST_BXFILT_REST,EXIST_BXFILT_OBS)
cc      print*,' xxx EXIST(BX) = ', EXIST_BXFILT_REST,EXIST_BXFILT_OBS

      RETURN
      END  ! end READ_CALIB_WRAPPER


C ==========================================
CDECK  ID>,  EXEC_READ_DATA. 
      SUBROUTINE EXEC_READ_DATA(IVERS,OPTMASK)

c Created Feb 2021
c Driver to read & analyze data for input version.
c Use logicals FORMAT_FITS and FORMAT_TEXT for format-specific
c function calls.
c This subroutine replaces legacy RDVERSION_FITS & RDVERSION_TEXT
c
c Oct 17 2023: read spectra only if using a REFORMAT option.
c
c ------

      IMPLICIT NONE

      INTEGER
     &   IVERS     ! (I) ! version index to read
     &  ,OPTMASK   ! (I) ! indicates GLOBAL or ALL


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c local var

      INTEGER   NSN_VERS, LEN_VERS, LEN_PATH, OPTRD
      INTEGER   IJOB, NJOBTOT, ISN, ISTAT
      LOGICAL   LRDFLAG_GLOBAL, LRDFLAG_ALL, LRDFLAG_SPEC
      LOGICAL   REFORMAT_LOCAL
      CHARACTER cVERSION*(MXCHAR_VERSION), cPATH*(MXCHAR_PATH)
      CHARACTER FNAM*16

c functions
      LOGICAL  LDONE_CIDLIST
      INTEGER  RD_SNFITSIO_PREP, RD_SNTEXTIO_PREP
      EXTERNAL RD_SNFITSIO_PREP, RD_SNTEXTIO_PREP
C --------------- BEGIN -----------

      FNAM = 'EXEC_READ_DATA'
      LRDFLAG_GLOBAL = ( OPTMASK .EQ. OPTMASK_SNDATA_GLOBAL)
      LRDFLAG_ALL    = ( OPTMASK .EQ. OPTMASK_SNDATA_ALL   )

      REFORMAT_LOCAL = (REFORMAT_SNANA .or. REFORMAT_SPECTRA_ONLY)
      LRDFLAG_SPEC   = (REFORMAT_LOCAL .or. USE_TABLEFILE_MARZ)
     &                 .and. (DEBUG_FLAG .NE. -333)  ! -333 suppresses reading SPEC

      ISNLC_VERSION    = IVERS

c get version and private data path for this version
      cVERSION = VERSION_PHOTOMETRY(ivers)
      LEN_VERS = INDEX(cVERSION,' ') - 1
      cVERSION = VERSION_PHOTOMETRY(ivers)(1:LEN_VERS) // char(0)

      LEN_PATH = INDEX(PRIVATE_DATA_PATH,' ') - 1
      cPATH    = PRIVATE_DATA_PATH(1:LEN_PATH) // char(0)

c read global info and store in SNDATA struct in sndata.h
      OPTRD = 0   ;
      IF ( FORMAT_FITS ) THEN
         IF ( LRDFLAG_GLOBAL )          OPTRD = OPTRD + 2
         IF ( .NOT. REFORMAT_SIMTRUTH ) OPTRD = OPTRD + 256
         NSN_VERS  = RD_SNFITSIO_PREP(OPTRD, cPATH, cVERSION,
     &                    LEN_PATH, LEN_VERS )
      ELSE
         IF ( DEBUG_FLAG == 1024 ) OPTRD = OPTRD + 1024 ! generic DUMP
         if ( LRDFLAG_GLOBAL .or. IVERS > 1 ) then
            NSN_VERS = RD_SNTEXTIO_PREP(OPTRD, cPATH, cVERSION,
     &              LEN_PATH, LEN_VERS)
         endif
      ENDIF

      IF ( NSN_VERS > MXSNLC-1 ) THEN
        write(C1err,161) NSN_VERS, MXSNLC
161     format('NSN_VERS=',I8,' exceeds bound MXSNLC=',I8 )
        C2err = 'Check MXSNLC parameter in snana.car'
        CALL MADABORT(FNAM, c1err, c2err )
      ENDIF

      N_SNLC_READ(IVERS) = NSN_VERS

c read SNDATA struct and tranfer global info to fortran variables
      if ( LRDFLAG_GLOBAL .OR. IVERS > 1 ) then
         CALL INIT_READ_OVERRIDE()      ! May 2023
         CALL RDGLOBAL_DRIVER()
         CALL INIT_SURVEY(NSN_VERS)     ! init a few things
         IF ( LRDFLAG_GLOBAL ) RETURN
      endif

c - - - - - - - -
c if we get here, read & process events

c strip off info for SPLITTING jobs among multiple CPUs.
      NJOBTOT = JOBSPLIT(2)    ! total number of split jobs
      IJOB    = JOBSPLIT(1)    ! do IJOB of NJOBTOT
      IF ( NJOBTOT .GT. 1 ) THEN
        write(6,20) JOBSPLIT
20      format(T5,'Process SPLIT-JOB ',I3,' of ', I3 )
      ENDIF

c ------------------------------------------------------
c LOOP OVER EVENTS

      DO 100 isn = IJOB, NSN_VERS, NJOBTOT ! every NJOBTOT'th SN

         IF ( N_SNLC_FITCUTS >= MXLC_FIT ) GOTO 100

         CALL INIT_SNLC()

         ! absolute index independent of cuts or SPLIT jobs;
         ! used as integer index if CID is a string (see CIDASSIGN)
         ABSO_INDEX = ABSO_OFFSET + isn

c read header for event and load SNDATA struct.
c Note that ISN is a fortran index starting at 1
        IF ( FORMAT_FITS ) THEN
           CALL RD_SNFITSIO_EVENT(OPTMASK_SNDATA_HEAD,ISN) ! C func
        ELSE IF ( FORMAT_TEXT ) THEN
           CALL RD_SNTEXTIO_EVENT(OPTMASK_SNDATA_HEAD,ISN) ! C func
        ENDIF

c transfer from C struct to global fortran variables
        CALL RDHEAD_DRIVER(istat)

        if ( ISTAT < 0 ) GOTO 100    ! failed cut on header var/CID



c Read observations for event and load SNDATA C-struct.
c Read optional SPECTRA and load GENSPEC C-struct.
c All reading is done here to avoid STORE_PARSE_WORDS conflicts below.
        IF ( FORMAT_FITS ) THEN
           CALL RD_SNFITSIO_EVENT(OPTMASK_SNDATA_OBS,ISN)
           IF ( LRDFLAG_SPEC ) THEN
              CALL RD_SNFITSIO_EVENT(OPTMASK_SNDATA_SPEC,ISN)
           ENDIF
        ELSE IF ( FORMAT_TEXT ) THEN
           CALL RD_SNTEXTIO_EVENT(OPTMASK_SNDATA_OBS, ISN)
           IF ( LRDFLAG_SPEC ) THEN
              CALL RD_SNTEXTIO_EVENT(OPTMASK_SNDATA_SPEC,ISN)
           ENDIF
        ENDIF

c transfer variables from C struct to fortran global variables

        CALL RDOBS_DRIVER()

        IF ( LRDFLAG_SPEC ) CALL RDSPEC_DRIVER(0)

c ---------------------------------------------------------------

         IF ( ISTAT .EQ. 0 ) THEN
            N_SNLC_PROC = N_SNLC_PROC + 1 ! number of processed LC
            call PRINT_RDSN()      ! print one-line summary

            CALL SNANA_DRIVER(ISN,N_SNLC_PROC)
         ENDIF

c stop reading if/when all CIDs are processed
        IF ( LDONE_CIDLIST() ) GOTO 500

 100  CONTINUE          ! end ISN loop

 500  CONTINUE

      ABSO_OFFSET = ABSO_OFFSET + N_SNLC_READ(IVERS)

      RETURN
      END   ! end EXEC_READ_DATA

C ==========================================
CDECK  ID>,  GETINFO_PHOT. 
      SUBROUTINE GETINFO_PHOTOMETRY(ivers)

c Shell to use getInfo_PHOTOMETRY_VERION() function to
c get path to data, full name of list file and
c full name of readme file. Also construct
c SNDATA_PREFIX
c

      IMPLICIT NONE

      INTEGER IVERS  ! (I) version index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LEN_VERS, istat, L1, L2, L3
      CHARACTER*(2*MXCHAR_FILENAME)
     &   VERSION, PATH, LIST_FILE, README_FILE
      CHARACTER FNAM*20, FIRST_WORD*60

      INTEGER   GETINFO_PHOTOMETRY_VERSION
      EXTERNAL  GETINFO_PHOTOMETRY_VERSION, CHECK_FILE_DOCANA

C ----------------- BEGIN --------------
      FNAM = "GETINFO_PHOTOMETRY"

      VERSION  = VERSION_PHOTOMETRY(ivers)
      LEN_VERS = INDEX(VERSION,' ') - 1
      VERSION  = VERSION(1:LEN_VERS)  // char(0)

      L1   =  INDEX(PRIVATE_DATA_PATH,' ') - 1
      PATH =  PRIVATE_DATA_PATH(1:L1) // char(0)

      ISTAT = GETINFO_PHOTOMETRY_VERSION (
     &               VERSION,                        ! input
     &               PATH, LIST_FILE, README_FILE,   ! returned
     &               LEN_VERS, L1, L2, L3 )

      L1 = INDEX(PATH,char(0)) - 1
      IF ( L1 > MXCHAR_PATH ) then
         CALL PRINT_PREABORT_BANNER(FNAM//char(0),40)
         print*,' SNDATA_PATH = ', PATH(1:L1)
         write(c1err,61) 'SNDATA_PATH', L1, MXCHAR_PATH
         write(c2err,62)
         CALL MADABORT(FNAM, C1err, C2err)
      ENDIF
      SNDATA_PATH = PATH(1:L1)           ! fill global

61    format('LEN(',A,')=',I3,
     &      ' is too long (MXCHAR_PATH=',I3,')')
161   format('LEN(',A,')=',I3,
     &      ' is too long (MXCHAR_FILENAME=',I3,')')
62    format('Check $SNDATA_ROOT');

      L2 = INDEX(LIST_FILE,char(0)) - 1
      IF ( L2 > MXCHAR_FILENAME ) then
         CALL PRINT_PREABORT_BANNER(FNAM//char(0),40)
         print*,' LIST_FILE = ', LIST_FILE(1:L2)

         write(c1err,161) 'LIST_FILE', L2, MXCHAR_FILENAME
         write(c2err,62)
         CALL MADABORT(FNAM, C1err, C2err)
      ENDIF

      SNLIST_FILE = LIST_FILE(1:L2)      ! fill global

      L3 = INDEX(README_FILE,char(0)) - 1
      IF ( L3 > MXCHAR_FILENAME ) then
         CALL PRINT_PREABORT_BANNER(FNAM//char(0),40)
         print*,' README_FILE = ', README_FILE(1:L3)
         write(c1err,161) 'README_FILE', L3, MXCHAR_FILENAME
         write(c2err,62)
         CALL MADABORT(FNAM, C1err, C2err)
      ENDIF
      SNREADME_FILE(IVERS) = README_FILE(1:L3)  ! fill global

      CALL CHECK_FILE_DOCANA(REQUIRE_DOCANA,README_FILE,MXCHAR_FILENAME)

c - - - - - - - -
c construct prefix = path/[version]
      SNDATA_PREFIX = SNDATA_PATH(1:L1) //
     &       '/'  // VERSION(1:LEN_VERS)

      RETURN
      END   ! end of GETINFO_PHOTOMETRY


C ==================================================
CDECK  ID>,  DUMP_README. 
      SUBROUTINE DUMP_README(IVERS)

c Created Jun 2011
c Dump README file to stdout for this version.
c
C Use global SNDATA_PREFIX to construct the name
C of the README file for this version.
c This code was moved from RDSNDATA so that it can be
c called for both TEXT and FITS format.
c
c Feb 26 2015: SNFILE_README already filled, so don't fill it here.
c Feb 14 2020: fix first abort message, use FNAM.
c

      IMPLICIT NONE

      INTEGER IVERS, IERR  ! (I/O)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER LEN_README, IERROPEN, L1, LL

      CHARACTER
     &   CMD*(MXCHAR_FILENAME+20)
     &  ,FILENAME*(MXCHAR_FILENAME)
     &  ,VERSION*(MXCHAR_VERSION)
     &  ,FNAM*12

      EXTERNAL READ_YAML_VALS

c --------------- BEGIN --------------

      IERR = 0
      FNAM = 'DUMP_README'

      L1 = INDEX( SNDATA_PREFIX, ' ' ) - 1

      FILENAME = SNREADME_FILE(IVERS)

      OPEN(UNIT = LUNDMP, FILE = FILENAME,
     &     IOSTAT = IERROPEN, STATUS='OLD')
      LEN_README = INDEX ( FILENAME, ' ' ) - 1
      CLOSE ( UNIT = LUNDMP )
      IF ( IERROPEN .NE. 0 ) THEN
        CALL PRINT_PREABORT_BANNER(FNAM(1:10)//char(0),10)
        print*,' FILENAME = ', FILENAME
        C1err = 'Could not find README file '
        C2err = 'For FILENAME above.'
        CALL MADABORT(FNAM, c1err, c2err )
      ENDIF


      LEN_README = INDEX ( FILENAME, ' ' ) - 1
      write(cmd,50) FILENAME(1:LEN_README)
50    format('cat ', A )

      VERSION  = VERSION_PHOTOMETRY(ivers)
      LL       = index(VERSION,' ') - 1

      GLOBAL_BANNER = " DUMP README FILE for VERSION "
     &       // VERSION(1:LL)
      CALL PRBANNER ( global_banner(1:80) )

      print*, cmd
        CALL FLUSH(6)
        CALL SYSTEM ( cmd )
        CALL FLUSH(6)
      print*,' '


      RETURN
      END    ! end DUMP_README


C ===========================================
CDECK  ID>,  RDGLOBAL. 
      SUBROUTINE RDGLOBAL_DRIVER()

c Created Feb 2021
c Refactor to use SNDATA struct; same for FITS and TEXT format.
c Transfer global variables from SNDATA struct to fortran:
c SURVEY, FILTERS, etc ...
c
c Apr 24 2021: read SIM_BIASCOR_MASK
c Oct 08 2021: read SIM_MODEL_INDEX
c Dec 02 2022: fix subtle (harmless?) bug setting ISCORRECT_SIGN_VPEC
c
      IMPLICIT NONE

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITSCOM. inserted below by ypatchy. 

c define external C functions to read from fits files

c max length of catenated strings from all epochs;
c e.g., FIELD
c Aug 31 2023: 40k -> 80k
c Nov 16 2023: 80k -> 160k

      INTEGER MXLEN_EPSTRING
      PARAMETER (MXLEN_EPSTRING = 160000 )

      INTEGER
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR  ! read string
     &  ,RD_SNFITSIO_INT  ! read int
     &  ,RD_SNFITSIO_SHT  ! read short int
     &  ,RD_SNFITSIO_FLT  ! read float
     &  ,RD_SNFITSIO_DBL  ! read double

      EXTERNAL
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR
     &  ,RD_SNFITSIO_INT
     &  ,RD_SNFITSIO_SHT
     &  ,RD_SNFITSIO_FLT
     &  ,RD_SNFITSIO_DBL
     &  ,SET_RDMASK_SNFITSIO ! void
     &  ,RD_SNFITSIO_CLOSE   ! void function

c Define index-lookup arrays used for faster reading of fits files
      INTEGER MXFITSPAR
      PARAMETER ( MXFITSPAR = 400 )

      INTEGER
     &   INDXFITS_HEAD(MXFITSPAR)    ! used in RDSNFITS_HEAD
     &  ,INDXFITS_EPCUTS(MXFITSPAR)  ! used in RDSNFITS_EPCUTS
     &  ,INDXFITS_PHOT(MXFITSPAR)    ! used in RDSNFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,SNFITSIO_CODE_IVERSION     ! FITSIO version used to write data

c defin epoch mask for which

      INTEGER
     &   EPOCH_RDMASK_SNFITSIO(MXEPOCH)  ! epochs to keep/reject

c define long fits-string returned by RD_SNFITSIO_STR
      CHARACTER STRFITS*(MXLEN_EPSTRING)

      COMMON / FITSCOM /  SNFITSIO_CODE_IVERSION
     &  ,INDXFITS_HEAD, INDXFITS_EPCUTS, INDXFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,EPOCH_RDMASK_SNFITSIO, STRFITS



C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


      REAL*8    DARRAY(MXEPOCH)
      INTEGER   OPT, LEN
      CHARACTER STRING*100
      LOGICAL   ISCORRECT_BUG, ISCORRECT_FIX

      LOGICAL   correct_sign_vpec_data
      EXTERNAL  correct_sign_vpec_data
C ------------------ BEGIN -------------

      OPT  = OPTMASK_SNDATA_GLOBAL
c     &     + OPTMASK_SNDATA_DUMP

      global_banner =
     &   "RDGLOBAL: FETCH GLOBAL SURVEY INFO from HEADER"
      CALL PRBANNER(global_banner(1:60) )

      SNANA_VERSION_DATA = ''
      CALL FETCH_SNDATA_WRAPPER("SNANA_VERSION",
     &     ONE, SNANA_VERSION_DATA, DARRAY, OPT)
      LEN = INDEX(SNANA_VERSION_DATA,' ') - 1

      ISCORRECT_SIGN_VPEC =
     &      correct_sign_vpec_data(SNANA_VERSION_DATA(1:LEN)//char(0))

      CALL FETCH_SNDATA_WRAPPER("SURVEY", ONE,
     &        SURVEY_NAME, DARRAY, OPT)

      IF ( .NOT. FREEZE_SURVEY_FILTERS ) THEN
         CALL FETCH_SNDATA_WRAPPER("FILTERS",
     &        ONE, SURVEY_FILTERS, DARRAY, OPT)
         NFILTDEF_READ = INDEX(SURVEY_FILTERS,' ')
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("DATATYPE",
     &     ONE, DATATYPE, DARRAY, OPT)

      ! set global logical based on DATATYPE
      IF ( DATATYPE(1:4) .EQ. 'DATA' ) THEN
         ! do nothing
      ELSE IF ( DATATYPE(1:9)  .EQ. 'SIM_SNANA' ) THEN
         LSIM_SNANA = .TRUE.   ! SNANA sim
      ELSE IF ( DATATYPE(1:10) .EQ. 'SIM_MAGOBS' ) THEN
         LSIM_MAGOBS = .TRUE.  ! e..g, fakes overlaid on images
      ELSE
        C1err = 'Unrecognized DATATYPE = ' // DATATYPE
        C2err = 'Check DATATYPE key in FITS header.'
        CALL MADABORT("RDGLOBAL", c1err, c2err )
      ENDIF

c Mar 2022: check option to re-write sims to look like real data
      IF ( LSIM_SNANA .and. .not. REFORMAT_SIMTRUTH ) then
          LSIM_SNANA = .FALSE.
          DATATYPE   = 'DATA'
      ENDIF

      ISJOB_SIM = (LSIM_SNANA .or. LSIM_MAGOBS)

      CALL FETCH_SNDATA_WRAPPER("NXPIX", ONE, STRING, DARRAY, OPT)
      SNLC_NXPIX = int(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("NYPIX", ONE, STRING, DARRAY, OPT)
      SNLC_NYPIX = int(DARRAY(1))

      CALL RDGLOBAL_PRIVATE(OPT)

      CALL RDGLOBAL_ZPHOT_Q(OPT)  ! May 2022

      IF ( LSIM_SNANA ) THEN
         CALL FETCH_SNDATA_WRAPPER("SIMLIB_FILE",
     &        ONE, SIMLIB_FILENAME, DARRAY, OPT)

         CALL FETCH_SNDATA_WRAPPER("SIMLIB_MSKOPT",
     &        ONE, STRING, DARRAY, OPT)
         SIMLIB_MSKOPT = int(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("SIMOPT_MWCOLORLAW",
     &        ONE, STRING, DARRAY, OPT)
         SIMOPT_MWCOLORLAW = int(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("SIMOPT_MWEBV",
     &        ONE, STRING, DARRAY, OPT)
         SIMOPT_MWEBV = int(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("SIM_MWRV",
     &        ONE, STRING, DARRAY, OPT)
         SIM_MWRV = SNGL(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("SIM_VARNAME_SNRMON",
     &        ONE, SIMNAME_SNRMON, DARRAY, OPT)

         CALL FETCH_SNDATA_WRAPPER("SIM_BIASCOR_MASK",
     &        ONE, STRING, DARRAY, OPT)
         SIM_BIASCOR_MASK = int(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("SIM_MODEL_INDEX",  ! Oct 8 2021
     &       ONE, STRING, DARRAY, OPT)
         SIM_MODEL_INDEX = INT(DARRAY(1))

         CALL RDGLOBAL_SIMSED(OPT)

         CALL FETCH_SNDATA_WRAPPER("PySEDMODEL",
     &       ONE, STRING, DARRAY, OPT)
         CALL RDGLOBAL_PySEDMODEL(OPT,STRING)

         CALL RDGLOBAL_LCLIB(OPT)

         CALL RDGLOBAL_SIM_HOSTLIB(OPT)

         CALL RDGLOBAL_SIM_COSPAR()

      ENDIF  ! end LSIM_SNANA block


      RETURN
      END  ! end RDGLOBAL_DRIVER


C =======================================
CDECK  ID>,  FETCH_SNDATA_WRAPPER. 
      SUBROUTINE FETCH_SNDATA_WRAPPER(KEY, NARG, STRINGVAL, DVAL, OPT)

c Created Feb 7 2021
c Fortran wrapper to call C function fetch_SNDATA
c Note that NARG must  be 1 for string; NARG can be >1 for DVALs
c Return STRINGVAL or DVAL

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FITSCOM. inserted below by ypatchy. 

c define external C functions to read from fits files

c max length of catenated strings from all epochs;
c e.g., FIELD
c Aug 31 2023: 40k -> 80k
c Nov 16 2023: 80k -> 160k

      INTEGER MXLEN_EPSTRING
      PARAMETER (MXLEN_EPSTRING = 160000 )

      INTEGER
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR  ! read string
     &  ,RD_SNFITSIO_INT  ! read int
     &  ,RD_SNFITSIO_SHT  ! read short int
     &  ,RD_SNFITSIO_FLT  ! read float
     &  ,RD_SNFITSIO_DBL  ! read double

      EXTERNAL
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR
     &  ,RD_SNFITSIO_INT
     &  ,RD_SNFITSIO_SHT
     &  ,RD_SNFITSIO_FLT
     &  ,RD_SNFITSIO_DBL
     &  ,SET_RDMASK_SNFITSIO ! void
     &  ,RD_SNFITSIO_CLOSE   ! void function

c Define index-lookup arrays used for faster reading of fits files
      INTEGER MXFITSPAR
      PARAMETER ( MXFITSPAR = 400 )

      INTEGER
     &   INDXFITS_HEAD(MXFITSPAR)    ! used in RDSNFITS_HEAD
     &  ,INDXFITS_EPCUTS(MXFITSPAR)  ! used in RDSNFITS_EPCUTS
     &  ,INDXFITS_PHOT(MXFITSPAR)    ! used in RDSNFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,SNFITSIO_CODE_IVERSION     ! FITSIO version used to write data

c defin epoch mask for which

      INTEGER
     &   EPOCH_RDMASK_SNFITSIO(MXEPOCH)  ! epochs to keep/reject

c define long fits-string returned by RD_SNFITSIO_STR
      CHARACTER STRFITS*(MXLEN_EPSTRING)

      COMMON / FITSCOM /  SNFITSIO_CODE_IVERSION
     &  ,INDXFITS_HEAD, INDXFITS_EPCUTS, INDXFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,EPOCH_RDMASK_SNFITSIO, STRFITS



c function args
      CHARACTER KEY*(*)       ! (I) key name
      INTEGER   NARG          ! (I) number of args to return
      CHARACTER STRINGVAL*(*) ! (O) string value for key
      REAL*8    DVAL(*)       ! (O) double value(s) for key
      INTEGER   OPT           ! (I) options: 1-> dump
c local args
      INTEGER   LEN_KEY, LEN_STR, LEN_WHAT, COPYFLAG
      LOGICAL   L_GLOBAL, L_HEAD, L_OBS, L_DUMP, L_REQUIRE
      CHARACTER cSTRING*(MXLEN_EPSTRING), FNAM*22
      CHARACTER cKEY*60, c1err*80, c2err*80, WHAT*8
      EXTERNAL  COPY_SNDATA_GLOBAL, COPY_SNDATA_HEAD
      EXTERNAL  COPY_SNDATA_OBS

c ------------ BEGIN ----------

      FNAM = 'FETCH_SNDATA_WRAPPER'
      L_GLOBAL  = ( IAND(OPT,OPTMASK_SNDATA_GLOBAL)   > 0 )
      L_HEAD    = ( IAND(OPT,OPTMASK_SNDATA_HEAD)     > 0 )
      L_OBS     = ( IAND(OPT,OPTMASK_SNDATA_OBS )     > 0 )
      L_DUMP    = ( IAND(OPT,OPTMASK_SNDATA_DUMP)     > 0 )
      L_REQUIRE = ( IAND(OPT,OPTMASK_SNDATA_REQUIRE ) > 0 )

      LEN_KEY = INDEX(KEY//' ',' ') - 1
      cKEY    = KEY(1:LEN_KEY) // char(0)

      DVAL(1) = -9.0 ; STRINGVAL = 'NOTSET'

      COPYFLAG = -1  ! flag to copy from SNDATA struct to cSTRING or DVAL

      IF ( L_GLOBAL ) THEN
         CALL copy_SNDATA_GLOBAL(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)
         WHAT = "GLOBAL"
      ELSE IF ( L_HEAD ) THEN
         CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)
         WHAT = "HEAD"
      ELSE IF ( L_OBS ) THEN
         CALL copy_SNDATA_OBS(copyFlag, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)
         WHAT = "OBS"
      ELSE
         write(C1ERR, '("Invalid OPT=",I6)' ) OPT
         C2ERR = 'KEY = ' // KEY
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF
cc      print*,' xxx FETCH_WRAP: ',cKEY, cSTRING


      LEN_STR   = INDEX(cSTRING,char(0)) - 1
      STRINGVAL = cSTRING(1:LEN_STR)
      LEN_WHAT  = INDEX(WHAT,' ') - 1

      if ( LEN_STR < 0 ) then
         LEN_STR   = INDEX(cSTRING//' ', ' ') - 1
         write(C1ERR,161) LEN_STR, MXLEN_EPSTRING
161      format('Returned strlen=', I6,' ~=  MXLEN_EPSTRING=', I6)
	 write(C2ERR,162) KEY, NARG
162      format('KEY=',A, 4x, 'NARG=', I6)
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

      if ( L_DUMP ) then
         write(6,66) WHAT(1:LEN_WHAT), KEY(1:LEN_KEY),
     &        STRINGVAL(1:LEN_STR), DVAL(1)
 66      format(' xxx FETCH_SNDATA_',A,': ',
     &        A,' = |', A, '|', 5x, G10.4 )
      endif

      RETURN
      END     ! end FETCH_SNDATA_WRAPPER.

C =======================================
CDECK  ID>,  FETCH_GENSPEC_WRAPPER. 
      SUBROUTINE FETCH_GENSPEC_WRAPPER(KEY, ISPEC, DVAL, OPT)

c Created Feb 18 2021
c Fortran wrapper to call C function copy_GENSPEC.
c Returns DVAL array. Calling function must be careful
c to provide adequate DVAL array size.
c

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FITSCOM. inserted below by ypatchy. 

c define external C functions to read from fits files

c max length of catenated strings from all epochs;
c e.g., FIELD
c Aug 31 2023: 40k -> 80k
c Nov 16 2023: 80k -> 160k

      INTEGER MXLEN_EPSTRING
      PARAMETER (MXLEN_EPSTRING = 160000 )

      INTEGER
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR  ! read string
     &  ,RD_SNFITSIO_INT  ! read int
     &  ,RD_SNFITSIO_SHT  ! read short int
     &  ,RD_SNFITSIO_FLT  ! read float
     &  ,RD_SNFITSIO_DBL  ! read double

      EXTERNAL
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR
     &  ,RD_SNFITSIO_INT
     &  ,RD_SNFITSIO_SHT
     &  ,RD_SNFITSIO_FLT
     &  ,RD_SNFITSIO_DBL
     &  ,SET_RDMASK_SNFITSIO ! void
     &  ,RD_SNFITSIO_CLOSE   ! void function

c Define index-lookup arrays used for faster reading of fits files
      INTEGER MXFITSPAR
      PARAMETER ( MXFITSPAR = 400 )

      INTEGER
     &   INDXFITS_HEAD(MXFITSPAR)    ! used in RDSNFITS_HEAD
     &  ,INDXFITS_EPCUTS(MXFITSPAR)  ! used in RDSNFITS_EPCUTS
     &  ,INDXFITS_PHOT(MXFITSPAR)    ! used in RDSNFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,SNFITSIO_CODE_IVERSION     ! FITSIO version used to write data

c defin epoch mask for which

      INTEGER
     &   EPOCH_RDMASK_SNFITSIO(MXEPOCH)  ! epochs to keep/reject

c define long fits-string returned by RD_SNFITSIO_STR
      CHARACTER STRFITS*(MXLEN_EPSTRING)

      COMMON / FITSCOM /  SNFITSIO_CODE_IVERSION
     &  ,INDXFITS_HEAD, INDXFITS_EPCUTS, INDXFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,EPOCH_RDMASK_SNFITSIO, STRFITS



c function args
      CHARACTER KEY*(*)       ! (I) key name
      INTEGER   ISPEC         ! (I) spectrum index
      REAL*8    DVAL(*)       ! (O) double value(s) for key
      INTEGER   OPT           ! (I) options: 1-> dump
c local args
      INTEGER   LEN_KEY, COPYFLAG, cISPEC
      CHARACTER cKEY*60
      LOGICAL   L_DUMP
      EXTERNAL  COPY_GENSPEC

c ------------ BEGIN ----------

      LEN_KEY = INDEX(KEY//' ',' ') - 1
      cKEY    = KEY(1:LEN_KEY) // char(0)
      cISPEC  = ISPEC - 1  ! C index for GENSPEC

      DVAL(1) = -9.0 ! init output arg
      COPYFLAG = -1  ! flag to copy from GENSPEC struct to DVAL

      CALL copy_GENSPEC(COPYFLAG, cKEY, cISPEC, DVAL)

      L_DUMP   = ( IAND(OPT,OPTMASK_SNDATA_DUMP) > 0 )
      if ( L_DUMP ) then
         write(6,66) KEY(1:LEN_KEY), ISPEC, DVAL(1),DVAL(2),DVAL(3)
 66      format(' xxx FETCH_GENSPEC: ', A8, '(',I2,') = ', 3G12.3 )
      endif

      RETURN
      END     ! end FETCH_GENSPEC_WRAPPER.


C =================================
CDECK  ID>,  RDGLOB_PRIVATE. 
      SUBROUTINE RDGLOBAL_PRIVATE(OPT)

c Refactored Feb 2021 to use SNDATA struct in sndata.h.
c  (previous name was RDPRIVATE_FITS)
c Read/parse names of PRIVATE keys from header if NVAR_PRIVATE > 0
c

      IMPLICIT NONE

      INTEGER   OPT  ! (I)  1 -> dump flag for FETCH_SNDATA_WRAPPER


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN




      INTEGER   IVAR, LEN
      REAL*8    DARRAY(MXVAR_PRIVATE)
      CHARACTER DUMSTRING*10, cnum*2, KEYNAME*20, KEYWORD*60
      CHARACTER VARNAME(20)*60
      LOGICAL   MATCH_VARNAME

C -------------- BEGIN ---------------

      CALL FETCH_SNDATA_WRAPPER("NVAR_PRIVATE",
     &     ONE, DUMSTRING, DARRAY, OPT)
      NVAR_PRIVATE = int(DARRAY(1))

cc      print*,' xxx OPT, NVAR_PRIVATE = ', OPT, NVAR_PRIVATE

      IF ( NVAR_PRIVATE .LE. 0 ) RETURN

      IF( NVAR_PRIVATE > MXVAR_PRIVATE ) THEN
         write(C1ERR,61) NVAR_PRIVATE, MXVAR_PRIVATE
 61      format('NVAR_PRIVATE=',I4,' exceeds MXVAR_PRIVATE=',I4 )
         C2ERR = 'Check XXX_HEAD.FITS file'
         CALL MADABORT("RDGLOBAL_PRIVATE", C1ERR, C2ERR)
      ENDIF
c ----------------------------------------------

      DO 100 ivar = 1, NVAR_PRIVATE

        if ( ivar < 10 ) then
           write(cnum, '(I1)') ivar
        else
           write(cnum, '(I2)') ivar
        endif

        KEYNAME = "PRIVATE" // CNUM
        CALL FETCH_SNDATA_WRAPPER(KEYNAME,
     &     ONE, KEYWORD, DARRAY, OPTMASK_SNDATA_GLOBAL )

        PRIVATE_KEYWORD(ivar) = KEYWORD    ! load common block
        CALL PARSE_PRIVATE_KEYWORD(KEYWORD,ivar)

100   CONTINUE

      CALL FLUSH(6)

      RETURN
      END  ! end of RDGLOBAL_PRIVATE


C =================================
CDECK  ID>,  RDGLOB_ZPHOT_Q. 
      SUBROUTINE RDGLOBAL_ZPHOT_Q(OPT)

c Created May 12 2022
c Read/parse names host galaxy photo-z quantiles that determine
c column names. E.g., percentile 20 means HOSTGAL_ZPHOT_Q020 exists.
c

      IMPLICIT NONE

      INTEGER   OPT  ! (I)  1 -> dump flag for FETCH_SNDATA_WRAPPER


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



      INTEGER   IVAR, q, PCT
      REAL*8    DARRAY(MXZPHOT_Q)
      CHARACTER DUMSTRING*10, cnum*2, KEYNAME*20, KEYWORD*80

C -------------- BEGIN ---------------

      CALL FETCH_SNDATA_WRAPPER("NZPHOT_Q",
     &     ONE, DUMSTRING, DARRAY, OPT)
      SNHOST_NZPHOT_Q = int(DARRAY(1))

      IF ( SNHOST_NZPHOT_Q .LE. 0 ) RETURN

      IF( SNHOST_NZPHOT_Q > MXZPHOT_Q ) THEN
         write(C1ERR,61) SNHOST_NZPHOT_Q, MXZPHOT_Q
 61      format('NZPHOT_Q=',I4,' exceeds MXZPHOT_Q=',I4 )
         C2ERR = 'Check XXX_HEAD.FITS file'
         CALL MADABORT("RDGLOBAL_ZPHOT_Q", C1ERR, C2ERR)
      ENDIF
c ----------------------------------------------

      DO 100 ivar = 1, SNHOST_NZPHOT_Q

        q = ivar - 1 ! C index 0 to N-1
        write(cnum, '(I2.2)') q
        KEYNAME = "PERCENTILE_ZPHOT_Q" // CNUM
        CALL FETCH_SNDATA_WRAPPER(KEYNAME,
     &     ONE, KEYWORD, DARRAY, OPTMASK_SNDATA_GLOBAL )

        PCT = INT(DARRAY(1))
        SNHOST_ZPHOT_PERCENTILE(ivar) = SNGL(DARRAY(1))

c load varname for each HOSTGAL match; e.g., HOSTGAL_ZPHOT_Q030
        write(VARNAME_ZPHOT_Q(1,ivar),102) 'HOSTGAL',  PCT
        write(VARNAME_ZPHOT_Q(2,ivar),102) 'HOSTGAL2', PCT
102     format(A,'_ZPHOT_Q', I3.3)

100   CONTINUE

      write(6,40) SNHOST_NZPHOT_Q
40    format(T5,'Found NZPHOT_Q = ', I3, ' quantiles for HOST-zPHOT')
      CALL FLUSH(6)

      RETURN
      END  ! end of RDGLOBAL_ZPHOT_Q

C =======================================
CDECK  ID>,  RDGLOB_SIMSED. 
      SUBROUTINE RDGLOBAL_SIMSED(OPT)

c Refactored Feb 2021 (previous name: RDFITSHEAD_SIMSED_LEGACY)
c Read/parse SIMSED keys from header if NPAR_SIMSED exists.
c

      IMPLICIT NONE
      INTEGER OPT   ! (I) 1 -> dump


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FITSCOM. inserted below by ypatchy. 

c define external C functions to read from fits files

c max length of catenated strings from all epochs;
c e.g., FIELD
c Aug 31 2023: 40k -> 80k
c Nov 16 2023: 80k -> 160k

      INTEGER MXLEN_EPSTRING
      PARAMETER (MXLEN_EPSTRING = 160000 )

      INTEGER
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR  ! read string
     &  ,RD_SNFITSIO_INT  ! read int
     &  ,RD_SNFITSIO_SHT  ! read short int
     &  ,RD_SNFITSIO_FLT  ! read float
     &  ,RD_SNFITSIO_DBL  ! read double

      EXTERNAL
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR
     &  ,RD_SNFITSIO_INT
     &  ,RD_SNFITSIO_SHT
     &  ,RD_SNFITSIO_FLT
     &  ,RD_SNFITSIO_DBL
     &  ,SET_RDMASK_SNFITSIO ! void
     &  ,RD_SNFITSIO_CLOSE   ! void function

c Define index-lookup arrays used for faster reading of fits files
      INTEGER MXFITSPAR
      PARAMETER ( MXFITSPAR = 400 )

      INTEGER
     &   INDXFITS_HEAD(MXFITSPAR)    ! used in RDSNFITS_HEAD
     &  ,INDXFITS_EPCUTS(MXFITSPAR)  ! used in RDSNFITS_EPCUTS
     &  ,INDXFITS_PHOT(MXFITSPAR)    ! used in RDSNFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,SNFITSIO_CODE_IVERSION     ! FITSIO version used to write data

c defin epoch mask for which

      INTEGER
     &   EPOCH_RDMASK_SNFITSIO(MXEPOCH)  ! epochs to keep/reject

c define long fits-string returned by RD_SNFITSIO_STR
      CHARACTER STRFITS*(MXLEN_EPSTRING)

      COMMON / FITSCOM /  SNFITSIO_CODE_IVERSION
     &  ,INDXFITS_HEAD, INDXFITS_EPCUTS, INDXFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,EPOCH_RDMASK_SNFITSIO, STRFITS


      INTEGER   ipar, ipar_read, LENWD, IPAR_OFF, OPT_LOCAL
      REAL*8    DARRAY(MXPAR_SIMSED)
      CHARACTER DUM*20, KEYNAME*40, KEYWORD*80, c2*2, PARNAME*60

C -------------- BEGIN ---------------

      OPT_LOCAL = OPT

      CALL FETCH_SNDATA_WRAPPER("SIMSED_NPAR",ONE,DUM,DARRAY,OPT_LOCAL)
      NPAR_SIMSED = int(DARRAY(1))

      IF ( NPAR_SIMSED .LE. 0 ) RETURN

c ----------------------------------------------
c SIMSED before Dec 2018 had SIMSED_PAR01  to SIMSED_PAR[NN].
c After refactor, it is SIMSED_PAR00 to N-1.
c For back compatibility, check for SIMSED_PAR00/

      CALL FETCH_SNDATA_WRAPPER("SIMSED_PAR00",
     &     ONE, KEYNAME, DARRAY, OPT_LOCAL)

      IF ( INDEX(KEYNAME,' ') > 2 ) THEN
         IPAR_OFF = 0  ! 0 to N-1 for SIMSED index after Dec 2018
      ELSE
         IPAR_OFF = 1  ! 1-N before Dec 2018 (e.g., PLASTICC)
      ENDIF

      DO 100 ipar = 1, NPAR_SIMSED
        ipar_read = ipar + IPAR_OFF - 1   ! C-like index
        write(c2, '(I2.2)' ) ipar_read
        KEYNAME = "SIMSED_PAR" // C2 // char(0)
        CALL FETCH_SNDATA_WRAPPER(KEYNAME,ONE,KEYWORD,DARRAY,OPT_LOCAL)

        LENWD = INDEX(KEYWORD,' ') - 1
        CALL PARSE_PARENTHESES(KEYWORD(1:LENWD), PARNAME)
        SIMSED_KEYWORD(IPAR) = KEYWORD(1:LENWD) ! key(varname)
        SIMSED_PARNAME(IPAR) = PARNAME(1:20)    ! extracted varname

100   CONTINUE


      CALL FLUSH(6)

      RETURN
      END  ! end of RDGLOBAL_SIMSED

C =======================================
CDECK  ID>,  RDGLOB_PySEDMODEL. 
      SUBROUTINE RDGLOBAL_PySEDMODEL(OPT,MODEL_NAME)

c Created Dec 10 2018
c Refactored Feb 2021 to use SNDATA struct.
c
c Read/parse PySEDMODEL keys from header if NPAR_[BYOSED,SNEMO] exists.

      IMPLICIT NONE

      INTEGER   OPT            ! (I) 1 -> dump
      CHARACTER MODEL_NAME*(*) ! (I) e.g., 'BYOSED', 'SNEMO'

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER   ipar, LENM, LENVAL, NPAR_LOCAL
      CHARACTER KEYNAME*80, KEYVAL*80, c2*2, PARNAME*60
      LOGICAL   LDMP, LVALID
      REAL*8    DARRAY(4)

C -------------- BEGIN ---------------

      LENM   = INDEX(MODEL_NAME,' ') - 1
      LVALID = .FALSE.
      IF ( MODEL_NAME(1:6) .EQ. 'BYOSED' ) LVALID = .TRUE.
      IF ( MODEL_NAME(1:5) .EQ. 'SNEMO'  ) LVALID = .TRUE.

c      print*,'    xxx MODEL_NAME, LVALID = ',
c     &      MODEL_NAME(1:LENM), LVALID

      if ( .not. LVALID ) RETURN

      KEYNAME   = MODEL_NAME(1:LENM) // "_NPAR"
      CALL FETCH_SNDATA_WRAPPER(KEYNAME, ONE, KEYVAL, DARRAY, OPT)

      LDMP = .FALSE.
      IF ( LDMP ) THEN
         print*,' xxx -------------------------------------- '
         print*,' xxx **** DUMP RDFITSHEAD_PySEDMODEL ***** '
         print*,' xxx MODEL_NAME = ', MODEL_NAME
         print*,' xxx KEYNAME    = ', KEYNAME(1:40)
         print*,' xxx KEYVAL     = ', KEYVAL(1:40)
      ENDIF

      NPAR_LOCAL = int(DARRAY(1))
      IF ( NPAR_LOCAL .LE. 0 ) RETURN

c ----------------------------------------------
c load global NPAR and MODEL_NAME
      NPAR_PySEDMODEL = NPAR_LOCAL
      PySEDMODEL_NAME = MODEL_NAME(1:LENM)

      DO 100 ipar = 1, NPAR_PySEDMODEL
        write(c2, '(I2.2)') ipar-1
        KEYNAME = MODEL_NAME(1:LENM) // "_PAR" // C2

        CALL FETCH_SNDATA_WRAPPER(KEYNAME, ONE, KEYVAL, DARRAY, OPT)

        LENVAL  = INDEX(KEYVAL,' ') - 1

        CALL PARSE_PARENTHESES(KEYVAL(1:LENVAL), PARNAME)
        PySEDMODEL_KEYWORD(IPAR) = KEYVAL(1:LENVAL) ! key(varname)
        PySEDMODEL_PARNAME(IPAR) = PARNAME(1:20)  ! extracted varname

100   CONTINUE

      CALL FLUSH(6)

      RETURN
      END  ! end of RDGLOBAL_PySEDMODEL

C =======================================
CDECK  ID>,  RDGLOB_LCLIB. 
      SUBROUTINE RDGLOBAL_LCLIB(OPT)

c Feb 2018
c Read/parse LCLIB keys from header if NPAR_LCLIB exists.
c

      IMPLICIT NONE

      INTEGER  OPT  ! (I)

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER   ipar, LENVAL
      REAL*8    DARRAY(4)
      CHARACTER KEYNAME*80, KEYVAL*80, c2*2, PARNAME*60

C -------------- BEGIN ---------------

      CALL FETCH_SNDATA_WRAPPER("LCLIB_NPAR",
     &       ONE, KEYVAL, DARRAY, OPT)

      NPAR_LCLIB = INT(DARRAY(1))
      IF ( NPAR_LCLIB .LE. 0 ) RETURN

c ----------------------------------------------

      DO 100 ipar = 1, NPAR_LCLIB
        write(c2, '(I2.2)') ipar-1
        KEYNAME = "LCLIB_PAR" // C2
        CALL FETCH_SNDATA_WRAPPER(KEYNAME,
     &       ONE, KEYVAL, DARRAY, OPT)

        LENVAL  = INDEX(KEYVAL,' ') - 1
        CALL PARSE_PARENTHESES(KEYVAL(1:LENVAL), PARNAME)
        LCLIB_KEYWORD(IPAR) = KEYVAL(1:LENVAL) ! key(varname)
        LCLIB_PARNAME(IPAR) = PARNAME(1:20)  ! extracted varname

100   CONTINUE
      CALL FLUSH(6)
      RETURN
      END  ! end of RDGLOBAL_LCLIB

C =======================================
CDECK  ID>,  RDGLOBAL_HOSTLIB. 
      SUBROUTINE RDGLOBAL_SIM_HOSTLIB(OPT)

c Created Feb 2021 [refactored from RDFITSHEAD_SIM_HOSTLIB]
c Read/parse SIM_HOSTLIB keys from header if NPAR_SIM_HOSTLIB exists.
c These are extra HOSTLIB params used in wgtmaps, etc ...

      IMPLICIT NONE

      INTEGER OPT  ! (I)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER   ipar, LENVAL
      REAL*8    DARRAY(4)
      CHARACTER KEYNAME*80, KEYVAL*80, c2*2, PARNAME*60

C -------------- BEGIN ---------------

      CALL FETCH_SNDATA_WRAPPER("SIM_HOSTLIB_NPAR",
     &       ONE, KEYVAL, DARRAY, OPT)

      NPAR_SIM_HOSTLIB = INT(DARRAY(1))
      IF ( NPAR_SIM_HOSTLIB .LE. 0 ) RETURN
c ----------------------------------------------

      DO 100 ipar = 1, NPAR_SIM_HOSTLIB
        write(c2, '(I2.2)' ) ipar-1  ! C like index
        KEYNAME = "SIM_HOSTLIB_PAR" // C2

        CALL FETCH_SNDATA_WRAPPER(KEYNAME,
     &       ONE, KEYVAL, DARRAY, OPT)

        LENVAL = INDEX(KEYVAL,' ') - 1
        CALL PARSE_PARENTHESES(KEYVAL(1:LENVAL), PARNAME)
        SIM_HOSTLIB_KEYWORD(IPAR) = KEYVAL(1:LENVAL) ! key(varname)
        SIM_HOSTLIB_PARNAME(IPAR) = PARNAME ! extracted varname

100   CONTINUE
      CALL FLUSH(6)
      RETURN
      END  ! end of RDGLOBAL_SIM_HOSTLIB

C ========================================
CDECK  ID>,  RDGLOBAL_SIM_COSPAR. 
      SUBROUTINE RDGLOBAL_SIM_COSPAR()
c
c Created Mar 2023
c Read simulated cosmology parameters from yaml-README
c (instead of from data header)

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



      INTEGER LEN
      REAL*8 SIM_COSPAR(20)
      CHARACTER FNAM*24, KEYLIST*100, FILENAME*(MXCHAR_FILENAME)

c ------------- BEGIN --------------

      FNAM    = 'RDGLOBAL_SIM_COSPAR' // char(0)
      KEYLIST = 'OMEGA_MATTER,OMEGA_LAMBDA,w0_LAMBDA,wa_LAMBDA,MUSHIFT'
     &           //char(0)

      LEN = INDEX(SNREADME_FILE(1),' ') - 1
      FILENAME = SNREADME_FILE(1)(1:LEN) // char(0)

      CALL READ_YAML_VALS(FILENAME, KEYLIST, FNAM,
     &                      SIM_COSPAR) ! return SIM_COSPAR

c store cosmo params in globals

      SIM_OM = SIM_COSPAR(1)
      SIM_OL = SIM_COSPAR(2)
      SIM_w0 = SIM_COSPAR(3)
      SIM_wa = SIM_COSPAR(4)
      SIM_MUSHIFT = SIM_COSPAR(5)

      RETURN
      END   ! end RDGLOBAL_SIM_COSPAR

C ===========================================
CDECK  ID>,  RDHEAD_DRIVER. 
      SUBROUTINE RDHEAD_DRIVER(ISTAT)

c Created Feb 2021 [refactored from PARSE_HEAD]
c Read header info and apply a few selection cuts to rapidly
c select small subsets:
c
c   CID
c   SNTYPE
c   REDSHIFT_ERR ??
c
      IMPLICIT NONE

      INTEGER ISTAT  ! (O) < 0 -> reject event


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER OPT, igal, CID
      REAL*8  DARRAY(10), TMPCUT
      CHARACTER STRING*100, FNAM*14
      LOGICAL   USECID

c functions
      INTEGER  GET_IDSURVEY
      LOGICAL  PASS_SNTYPE
      EXTERNAL RD_SNFITSIO_EVENT, RD_SNTEXTIO_EVENT

C -------------- BEGIN ------------

      ISTAT = 0
      FNAM  = 'RDHEAD_DRIVER'

c - - - - -
c fetch SNDATA values and load fortran globals

      OPT = OPTMASK_SNDATA_HEAD
c     &    + OPTMASK_SNDATA_DUMP

      DARRAY(1) = -999.0
      STRING    = ''

      CALL FETCH_SNDATA_WRAPPER("SUBSURVEY",
     &     ONE, STRING, DARRAY, OPT)
      IF ( INDEX(STRING,' ') > 2 ) THEN
         SUBSURVEY_NAME = STRING(1:MXCHAR_SURVEY)
         IDSUBSURVEY    = GET_IDSURVEY(SUBSURVEY_NAME)
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SNID",
     &     ONE, SNLC_CCID, DARRAY, OPT)
      ISNLC_LENCCID = INDEX(SNLC_CCID,' ') - 1
      call checkString_CCID(SNLC_CCID)   ! abort if illegal char in name

      CALL FETCH_SNDATA_WRAPPER("IAUC",
     &     ONE, SNLC_IAUC, DARRAY, OPT)
      ISNLC_LENCCID = INDEX(SNLC_CCID,' ') - 1
      call checkString_CCID(SNLC_CCID)   ! abort if illegal char in name
      ISNLC_LENIAUC = INDEX(SNLC_IAUC,' ') - 1
      IF ( WRTABLEFILE_IAUC .and. ISNLC_LENIAUC > 0 ) THEN
         SNLC_CCID      = SNLC_IAUC
         ISNLC_LENCCID  = ISNLC_LENIAUC
         call checkString_CCID(SNLC_CCID) ! abort if illegal char in name
      ENDIF

c - - - - - - - - - - - - - - - - - - - - - - - - - -
c Convert CCID to integer CID, and check if this CCID is selected.
      CALL PARSE_CID( SNLC_CCID, SNLC_IAUC,    ! inputs
     &                  CID, USECID)           ! returns args
      SNLC_CID  = CID   ! load integer CID
      if ( .NOT. USECID ) then
         ISTAT = ISTAT_SKIP;  RETURN
      endif
c - - - - - - - - - - - - - - - - - - - - - - - - - -

      CALL FETCH_SNDATA_WRAPPER("FAKE",
     &     ONE, STRING, DARRAY, OPT)
      ISNLC_FAKE = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("RA",  ONE, STRING, DARRAY,  OPT)
      SNLC8_RA = DARRAY(1)

      CALL FETCH_SNDATA_WRAPPER("DEC", ONE, STRING, DARRAY, OPT)
      SNLC8_DEC = DARRAY(1)

      CALL FETCH_SNDATA_WRAPPER("PIXSIZE", ONE, STRING, DARRAY, OPT)
      SNLC_PIXSIZE = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("NXPIX", ONE, STRING, DARRAY, OPT)
      SNLC_NXPIX = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("NYPIX", ONE, STRING, DARRAY, OPT)
      SNLC_NYPIX = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SNTYPE", ONE, STRING, DARRAY, OPT)
      ISNLC_TYPE = INT(DARRAY(1))
      IF ( ISNLC_TYPE == -9 ) ISNLC_TYPE = 0 ! Jun 17 2022
      IF ( .NOT. PASS_SNTYPE(ISNLC_TYPE) ) THEN
         ISTAT = ISTAT_SKIP;  RETURN
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("MWEBV", ONE, STRING, DARRAY, OPT)
      SNLC_MWEBV = SNGL(DARRAY(1))
      SNLC_MWEBV_ERR = SNLC_MWEBV * sngl(XTMW_FRACERR)  ! default error

      TMPCUT = 1.0E-12
      IF ( RESTORE_MWEBV_ERR_BUG ) TMPCUT = 0.001
      CALL FETCH_SNDATA_WRAPPER("MWEBV_ERR", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) .GE. TMPCUT ) THEN
         SNLC_MWEBV_ERR = SNGL(DARRAY(1))  ! override default error
      ENDIF

c - - - - -
c read MJD-related variables (PEAK, trigger, first & last detection)
      CALL FETCH_SNDATA_WRAPPER("PEAKMJD", ONE, STRING, DARRAY, OPT)
      SNLC_SEARCH_PEAKMJD = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("MJD_TRIGGER",
     &        ONE, STRING, DARRAY, OPT)
      SNLC8_MJD_TRIGGER = DARRAY(1)

      CALL FETCH_SNDATA_WRAPPER("MJD_DETECT_FIRST",
     &        ONE, STRING, DARRAY, OPT)
      SNLC8_MJD_DETECT_FIRST = DARRAY(1)

      CALL FETCH_SNDATA_WRAPPER("MJD_DETECT_LAST",
     &        ONE, STRING, DARRAY, OPT)
      SNLC8_MJD_DETECT_LAST = DARRAY(1)

c - - - - - -

      CALL FETCH_SNDATA_WRAPPER("NOBS", ONE, STRING, DARRAY, OPT)
      ISNLC_NEWMJD_FOUND = INT(DARRAY(1))

      CALL RDHEAD_REDSHIFT(OPT)

      DO igal = 1, MXSNHOST
         CALL RDHEAD_HOSTGAL(OPT,igal)
      ENDDO

      CALL RDHEAD_PRIVATE(OPT)

      IF ( LSIM_SNANA ) THEN
         CALL RDHEAD_SIM_SNANA(OPT)

c   reject event if user doesn't want to process true SNIa or NONIa
         if ( .NOT. USESIM_SNIA  .and. LSIM_TRUE_SNIa) THEN
	     ISTAT = ISTAT_SKIP ; RETURN
	 endif
         if ( .NOT. USESIM_NONIa .and. LSIM_TRUE_NONIa)  THEN
	    ISTAT = ISTAT_SKIP; RETURN
         endif

      ENDIF

      RETURN
      END   ! end RDHEAD_DRIVER

C ============================================
CDECK  ID>,  RDHEAD_PRIVATE. 
      SUBROUTINE RDHEAD_PRIVATE(OPT)

c Created Feb 2021 to read PRIVATE variables (pass from SNDATA struct)

      IMPLICIT NONE

      INTEGER OPT    ! OPT is arg for WRAPPER


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



      INTEGER ivar, NVAR
      REAL*8 DARRAY(4)
      CHARACTER STRING*12, KEY*60

C ------------ BEGIN ---------

      NVAR = NVAR_PRIVATE
      DO ivar = 1, NVAR
         KEY  = PRIVATE_KEYWORD(IVAR)
         CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
         PRIVATE_VALUE(IVAR) = DARRAY(1)
      ENDDO

      RETURN
      END   ! end RDHEAD_PRIVATE

C ============================================
CDECK  ID>,  RDHEAD_HOSTGAL. 
      SUBROUTINE RDHEAD_HOSTGAL(OPT,igal)

C Created Feb 9 2021 [refactored from PARSE_HOSTGAL]
c Transfer HOSTGAL info from SNDATA struct (sndata.h)
c to common block variable.s
c
c Mar 25 2021: fix bug setting EXIST_SNHOST_SB
c May 11 2021: read HOSTGAL_MAG (forgotten in I/O refactor)
c May 21 2021: read HOSTGAL_FLAG
c May 11 2022: read ZPHOT_Q

      IMPLICIT NONE

      INTEGER OPT, igal  ! OPT is arg for WRAPPER, igal is host index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK

      INTEGER   LENPRE, ifilt, q
      CHARACTER PREFIX*20, STRING*40, KEY*60, KEY_PREFIX*60
      REAL*8    DARRAY(MXFILT_OBS), SB, MAG, zq
      LOGICAL LTMP, LZQ

C -------------- BEGIN ----------

      CALL SET_HOSTGAL_PREFIX(IGAL,PREFIX,LENPRE)

C Start with items that only appear once;
c i.e., do not depend on host-match.

      IF ( IGAL == 1 ) THEN

         CALL FETCH_SNDATA_WRAPPER("HOSTGAL_NMATCH",
     &        ONE, STRING, DARRAY, OPT)
         SNHOST_NMATCH = INT(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("HOSTGAL_NMATCH2",
     &        ONE, STRING, DARRAY, OPT)
         SNHOST_NMATCH2 = INT(DARRAY(1))

         KEY_PREFIX = "HOSTGAL_SB_FLUXCAL"
         CALL RDHEAD_FILTERLOOP(KEY_PREFIX, SNHOST_SBFLUXCAL, OPT)
         DO ifilt = 1, NFILTDEF_READ
            SB = SNHOST_SBFLUXCAL(ifilt)
            if ( SB > -998.0 ) EXIST_SNHOST_SB = .TRUE.
         ENDDO

         KEY_PREFIX = "HOSTGAL_MAG"
         CALL RDHEAD_FILTERLOOP(KEY_PREFIX, SNHOST_MAGOBS, OPT)
         DO ifilt = 1, NFILTDEF_READ
            MAG   = SNHOST_MAGOBS(ifilt,1)
            if ( MAG > -998.0 ) EXIST_SNHOST_MAGOBS = .TRUE.
         ENDDO

         KEY_PREFIX = "HOSTGAL_SB_FLUXCAL"
         CALL RDHEAD_FILTERLOOP(KEY_PREFIX, SNHOST_SBFLUXCAL, OPT)
         DO ifilt = 1, NFILTDEF_READ
            SB = SNHOST_SBFLUXCAL(ifilt)
            if ( SB > -998.0 ) EXIST_SNHOST_SB = .TRUE.
         ENDDO

      ENDIF  ! end IGAL=1

c - - - - - - - -

      KEY    = PREFIX(1:LENPRE)//'_OBJID'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_OBJID(igal)  = INT8(DARRAY(1))
      DSNHOST_OBJID(igal) = DARRAY(1)

      KEY    = PREFIX(1:LENPRE)//'_FLAG'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_FLAG(igal)  = INT(DARRAY(1))

c - - -
      KEY    = PREFIX(1:LENPRE)//'_PHOTOZ'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_ZPHOT(igal)     = SNGL(DARRAY(1))

      KEY    = PREFIX(1:LENPRE)//'_PHOTOZ_ERR'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_ZPHOT_ERR(igal) = SNGL(DARRAY(1))

c read ZPHOT_Q (May 2022)
      if ( SNHOST_NZPHOT_Q > 0 ) then
        DO q = 1, SNHOST_NZPHOT_Q
          KEY = VARNAME_ZPHOT_Q(igal,q)
          CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
          SNHOST_ZPHOT_Q(igal,q) = SNGL(DARRAY(1))
        ENDDO

        SNHOST_QZPHOT_MEAN(igal) = -9.0
	SNHOST_QZPHOT_STD(igal)  = -9.0

c xxxxxxxxxx Apr 1 2024 mark delete xxxxxxxxx
c  BAD LOGIC BECAUSE IT TAKES EFFECT EVEN IF QUSNTILES ARE NOT REQUESTED
c
c	IF (igal == 1) THEN
c	   LTMP = (SNHOST_ZPHOT_Q(igal,1) < -0.001) .AND.
c     &        (SNLC_REDSHIFT > QUANTILE_ZERRMIN)
c	   IF (LTMP) SNLC_REDSHIFT = -9.0 ! Forced event to be rejected
c	ENDIF
c xxxxxxxxx end mark xxxxxxxxxx

c          print*,' xxx ------------------------------------------- '
c          print*,' xxx CID ,igal = ', SNLC_CCID, igal
c          print*,' xxx SNHOST_ZPHOT_Q = ', SNHOST_ZPHOT_Q(igal,1:12)
      endif

      IF ( SNHOST_ZPHOT(igal) > 0.0 ) EXIST_SNHOST_ZPHOT = .TRUE.
c - - - -

      KEY    = PREFIX(1:LENPRE)//'_SPECZ'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_ZSPEC(igal)     = SNGL(DARRAY(1))

      KEY    = PREFIX(1:LENPRE)//'_SPECZ_ERR'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_ZSPEC_ERR(igal)     = SNGL(DARRAY(1))

c - - -

      KEY  = PREFIX(1:LENPRE)//'_RA'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST8_RA(igal) = DARRAY(1)

      KEY  = PREFIX(1:LENPRE)//'_DEC'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST8_DEC(igal) = DARRAY(1)

      KEY  = PREFIX(1:LENPRE)//'_SNSEP'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_ANGSEP(igal) = SNGL(DARRAY(1))
      IF ( SNHOST_ANGSEP(igal) > 0.0 ) EXIST_SNHOST_ANGSEP = .TRUE.

      KEY  = PREFIX(1:LENPRE)//'_DDLR'
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_DDLR(igal) = SNGL(DARRAY(1))
      IF ( SNHOST_DDLR(igal) > 0.0 )  EXIST_SNHOST_DDLR = .TRUE.

c - - - - - - - - - - - -  -

      KEY    = PREFIX(1:LENPRE)//'_LOGMASS' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_LOGMASS(igal)   = SNGL(DARRAY(1))

      KEY    = PREFIX(1:LENPRE)//'_LOGMASS_ERR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_LOGMASS_ERR(igal)   = SNGL(DARRAY(1))

c xxx      if(SNHOST_LOGMASS(igal) > -9000.) EXIST_SNHOST_LOGMASS = .TRUE.
      EXIST_SNHOST_LOGMASS = .TRUE.

c - - - -

      KEY    = PREFIX(1:LENPRE)//'_LOGSFR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_LOGSFR(igal)     = SNGL(DARRAY(1))

      KEY    = PREFIX(1:LENPRE)//'_LOGSFR_ERR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_LOGSFR_ERR(igal)     = SNGL(DARRAY(1))

c xxx      IF(SNHOST_LOGSFR(igal) > -9000.0) EXIST_SNHOST_LOGSFR = .TRUE.
      EXIST_SNHOST_LOGSFR = .TRUE.
c - - - -

      KEY    = PREFIX(1:LENPRE)//'_LOGsSFR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_LOGsSFR(igal)     = SNGL(DARRAY(1))

      KEY    = PREFIX(1:LENPRE)//'_LOGsSFR_ERR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_LOGsSFR_ERR(igal)     = SNGL(DARRAY(1))

      IF(SNHOST_LOGsSFR(igal) > -9000.0) EXIST_SNHOST_LOGsSFR = .TRUE.

c - - - -

      KEY    = PREFIX(1:LENPRE)//'_COLOR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_COLOR(igal)     = SNGL(DARRAY(1))

      KEY    = PREFIX(1:LENPRE)//'_COLOR_ERR' ;
      CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
      SNHOST_COLOR_ERR(igal)     = SNGL(DARRAY(1))

      IF(SNHOST_COLOR(igal) > -9000.0) EXIST_SNHOST_COLOR = .TRUE.

c - - -
      KEY_PREFIX = PREFIX(1:LENPRE) // "_MAG"
      CALL RDHEAD_FILTERLOOP(KEY_PREFIX, SNHOST_MAGOBS(ifilt,igal), OPT)

      RETURN
      END    ! end RDHEAD_HOSTGAL

C ===========================================
CDECK  ID>,  RDHEAD_FILT. 
      SUBROUTINE RDHEAD_FILTERLOOP(KEY_PREFIX, FARRAY, OPT)

c Created Feb 2021
c Check keys KEY_PREFIX_[band] and return float FARRAY(ifilt).
c Mar 23 2021: fix bug using LENPRE

      IMPLICIT NONE

      CHARACTER KEY_PREFIX*(*)  ! (I) check keys KEY_PREFIX_[band]
      REAL      FARRAY(*)       ! (O) value vs. ifilt
      INTEGER   OPT             ! (I) argument for FETCH_SNDATA_WRAPPER


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER   IFILT, IFILT_OBS, LENPRE
      CHARACTER STRING*10, BAND*2, KEY*60
      REAL*8    DARRAY(4)

C --------------- BEGIN ---------

      LENPRE = INDEX(KEY_PREFIX//' ',' ') - 1

      DO ifilt     = 1, NFILTDEF_READ
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         band      = FILTDEF_STRING(ifilt_obs:ifilt_obs)
         KEY       = KEY_PREFIX(1:LENPRE) // '_' // band
         CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
         FARRAY(ifilt) = SNGL(DARRAY(1))

c         write(6,66) KEY, FARRAY(ifilt)     ! xxx
c66       format(' xxx ', A20,' = ', F12.5 ) ! xxx

      ENDDO
      RETURN
      END   ! end RDHEAD_FILTERLOOP

C ===========================================
CDECK  ID>,  RDHEAD_REDSHIFT. 
      SUBROUTINE RDHEAD_REDSHIFT(OPT)

c Created Feb 2021 [refactored from PARSE_REDSHIFT]
c Read/store redshift & vpec info
c Note tat REDSHIFT_FINAL is used for LC fitting.
c
c Jun 5 2021: no longer apply REDSHIFT_FINAL_SHIFT here; see SET_zSHIFT().
c
      IMPLICIT NONE

      INTEGER OPT    ! (I) argument for FETCH_SNDATA_WRAPPER


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER STRING*40
      REAL*8 DARRAY(10)

C ----------- BEGIN ------------

      CALL FETCH_SNDATA_WRAPPER("REDSHIFT_HELIO",
     &       ONE, STRING, DARRAY, OPT)
      SNLC_zHELIO = SNGL(DARRAY(1))
      SNLC_REDSHIFT = SNLC_zHELIO  ! used for LC fitting

      CALL FETCH_SNDATA_WRAPPER("REDSHIFT_HELIO_ERR",
     &       ONE, STRING, DARRAY, OPT)
      SNLC_zHELIO_ERR = SNGL(DARRAY(1))
      SNLC_REDSHIFT_ERR = SNLC_zHELIO_ERR

c - - - - -

      CALL FETCH_SNDATA_WRAPPER("REDSHIFT_FINAL",
     &       ONE, STRING, DARRAY, OPT)
      SNLC_zCMB = SNGL(DARRAY(1))  !


      CALL FETCH_SNDATA_WRAPPER("REDSHIFT_FINAL_ERR",
     &       ONE, STRING, DARRAY, OPT)
      SNLC_zCMB_ERR = SNGL(DARRAY(1))


c if no REDSHIFT_FINAL, try alternative REDSHIFT_CMB
c (beware that VPEC correction should NOT be included here)
      IF ( SNLC_zCMB < 0.0 ) THEN
         CALL FETCH_SNDATA_WRAPPER("REDSHIFT_CMB",
     &         ONE, STRING, DARRAY, OPT)
         SNLC_zCMB = SNGL(DARRAY(1))

         CALL FETCH_SNDATA_WRAPPER("REDSHIFT_CMB_ERR",
     &         ONE, STRING, DARRAY, OPT)
         SNLC_zCMB_ERR = SNGL(DARRAY(1))
      ENDIF

c - - - - - - - - - -
c assign light curve redshift if not already assigned by Z_HELIO
c i.e., light curve analysis should use Z_HELIO if it's defined;
c otherwise use Z_CMB

      IF ( SNLC_ZHELIO < 0.0 ) then
         SNLC_REDSHIFT      = SNLC_zCMB
         SNLC_REDSHIFT_ERR  = SNLC_zCMB_ERR
      ENDIF

c -------------------------
c VPEC

      CALL FETCH_SNDATA_WRAPPER("VPEC", ONE, STRING, DARRAY, OPT)
      SNLC_VPEC = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("VPEC_ERR", ONE, STRING, DARRAY, OPT)
      SNLC_VPEC_ERR = SNGL(DARRAY(1))

c Oct 26 2020: check option to fix VPEC sign convention in older FITS data
      if ( DOFIX_WRONG_SIGN_VPEC ) then
         SNLC_VPEC = -1.0 * SNLC_VPEC
      endif

      IF (  abs(VPEC_ERR_OVERRIDE) > .001 ) THEN
         SNLC_VPEC_ERR = VPEC_ERR_OVERRIDE  ! Jan 11 2018
      ENDIF

c redshift quality flag (real data only)
      CALL FETCH_SNDATA_WRAPPER("REDSHIFT_QUALITYFLAG",
     &    ONE, STRING, DARRAY, OPT)
      ISNLC_zFLAG = INT(DARRAY(1))

c mask redshift source (march 14 2024)
      CALL FETCH_SNDATA_WRAPPER("MASK_REDSHIFT_SOURCE",
     &    ONE, STRING, DARRAY, OPT)
      ISNLC_zSOURCE = INT(DARRAY(1))

      RETURN
      END    ! end RDHEAD_REDSHIFT

C =============================
CDECK  ID>,  RDHEAD_SIM_SNANA. 
      SUBROUTINE RDHEAD_SIM_SNANA(OPT)

      IMPLICIT NONE

      INTEGER OPT    ! (I) argument for FETCH_SNDATA_WRAPPER


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER ipar
      CHARACTER STRING*100, KEY*80
      REAL*8 DARRAY(10)

c functions
      INTEGER ISMODEL_SNIa

C ----------- BEGIN ----------

      STRING  = 'DUMMY'

      CALL FETCH_SNDATA_WRAPPER("SIM_MODEL_NAME",  ! e.g., SALT2, BYOSED
     &    ONE, STRING, DARRAY, OPT)
      SIMNAME_MODEL = STRING(1:MXCHAR_MODELNAME)

      CALL FETCH_SNDATA_WRAPPER("SIM_TYPE_NAME",  ! e.g., Ia, Ibc
     &    ONE, STRING, DARRAY, OPT)
      SIMNAME_TYPE = STRING(1:12)

      CALL FETCH_SNDATA_WRAPPER("SIM_MODEL_INDEX",
     &    ONE, STRING, DARRAY, OPT)
      SIM_MODEL_INDEX = INT(DARRAY(1))

        ! set TRUE_SNIa and NONIa  logicals (Apr 2024)
      LSIM_TRUE_SNIa = .FALSE.
      IF ( ISMODEL_SNIa(SIM_MODEL_INDEX) > 0 ) LSIM_TRUE_SNIa=.TRUE.
      LSIM_TRUE_NONIa = .NOT. LSIM_TRUE_SNIa

      CALL FETCH_SNDATA_WRAPPER("SIM_TYPE_INDEX",
     &    ONE, STRING, DARRAY, OPT)
      SIM_GENTYPE = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_TEMPLATE_INDEX",
     &    ONE, STRING, DARRAY, OPT)
      SIM_TEMPLATE_INDEX = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_SUBSAMPLE_INDEX",
     &    ONE, STRING, DARRAY, OPT)
      SIM_SUBSAMPLE_INDEX = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_LIBID",
     &    ONE, STRING, DARRAY, OPT)
      SIM_LIBID = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_NGEN_LIBID",
     &    ONE, STRING, DARRAY, OPT)
      SIM_NGEN_LIBID = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_NOBS_UNDEFINED",
     &    ONE, STRING, DARRAY, OPT)
      SIM_NOBS_UNDEFINED = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_SEARCHEFF_MASK",
     &    ONE, STRING, DARRAY, OPT)
      SIM_SEARCHEFF_MASK = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_REDSHIFT_HELIO",
     &    ONE, STRING, DARRAY, OPT)
      SIM_REDSHIFT_HELIO = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_REDSHIFT_CMB",
     &    ONE, STRING, DARRAY, OPT)
      SIM_REDSHIFT_CMB = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_REDSHIFT_HOST",
     &    ONE, STRING, DARRAY, OPT)
      SIM_REDSHIFT_HOST = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_REDSHIFT_FLAG",
     &    ONE, STRING, DARRAY, OPT)
      SIM_REDSHIFT_FLAG = INT(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_VPEC",
     &    ONE, STRING, DARRAY, OPT)
      SIM_VPEC = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_HOSTLIB_GALID",
     &    ONE, STRING, DARRAY, OPT)
      DSIM_HOSTLIB_GALID = DARRAY(1)
      SIM_HOSTLIB_GALID  = DSIM_HOSTLIB_GALID

      do ipar = 1, NPAR_SIM_HOSTLIB
         CALL FETCH_SNDATA_WRAPPER(SIM_HOSTLIB_KEYWORD(ipar),
     &        ONE, STRING, DARRAY, OPT)
         SIM_HOSTLIB_PARVAL(ipar) = SNGL(DARRAY(1))
      enddo

      CALL FETCH_SNDATA_WRAPPER("SIM_DLMU",
     &    ONE, STRING, DARRAY, OPT)
      SIM_DLMAG = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_LENSDMU",
     &    ONE, STRING, DARRAY, OPT)
      SIM_LENSDMU = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_MWEBV",
     &    ONE, STRING, DARRAY, OPT)
      SIM_MWEBV = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_PEAKMJD",
     &    ONE, STRING, DARRAY, OPT)
      SIM_PEAKMJD = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_MJD_EXPLODE",
     &    ONE, STRING, DARRAY, OPT)
      SIM_MJD_EXPLODE = SNGL(DARRAY(1))

c - - - - model params - - - - -

      CALL FETCH_SNDATA_WRAPPER("SIM_MAGSMEAR_COH",
     &    ONE, STRING, DARRAY, OPT)
      SIM_MAGSMEAR_COH = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_WGT_POPULATION",
     &    ONE, STRING, DARRAY, OPT)
      SIM_WGT_POPULATION = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2x0",
     &    ONE, STRING, DARRAY, OPT)
      SIM_SALT2x0 = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2mB",
     &    ONE, STRING, DARRAY, OPT)
      SIM_SALT2mB = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2c", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_COLORPAR     = SNGL(DARRAY(1))
         SIMNAME_COLORPAR = 'SIM_c'
         SIMNAME_COLORLAW = 'SIM_beta'
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2alpha",ONE,STRING,DARRAY,OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_SHAPELAW     = SNGL(DARRAY(1))
         SIMNAME_SHAPELAW = 'SIM_alpha'
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2beta",ONE,STRING,DARRAY,OPT)
      if ( DARRAY(1) > -8.0 )  SIM_COLORLAW = SNGL(DARRAY(1))

      CALL FETCH_SNDATA_WRAPPER("SIM_AV", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_AV = SNGL(DARRAY(1))
c copy SIM_AV as color param if NOT SALT2 model; otherwise leave
c SIM_AV as separate from SALT2c.
        if ( SIM_MODEL_INDEX .NE. MODEL_SALT2 ) then
           SIM_COLORPAR     =  SIM_AV
           SIMNAME_COLORPAR = 'SIM_AV'  ! Jul 2016: SIMAV->SIM_AV
           SIMNAME_COLORLAW = 'SIM_RV'  ! Jul 2016: SIMRV->SIM_RV
        endif

      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_RV", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_RV = SNGL(DARRAY(1))
         if ( SIM_MODEL_INDEX .NE. MODEL_SALT2 ) then
            SIM_COLORLAW = SIM_RV
         endif
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2gammaDM",
     &     ONE, STRING, DARRAY, OPT)
      SIM_SALT2gammaDM = SNGL(DARRAY(1))

c - - -  shape params - - - -

      CALL FETCH_SNDATA_WRAPPER("SIM_STRETCH", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_SHAPEPAR     = SNGL(DARRAY(1))
         SIMNAME_SHAPEPAR = 'SIM_STRETCH'
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_DELTA", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_SHAPEPAR     = SNGL(DARRAY(1))
         SIMNAME_SHAPEPAR = 'SIM_DELTA'
      ENDIF

c   Jun 2023 - check for THETA for BayeSN model
      CALL FETCH_SNDATA_WRAPPER("SIM_THETA", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_SHAPEPAR     = SNGL(DARRAY(1))
         SIMNAME_SHAPEPAR = 'SIM_THETA'
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_DM15", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_SHAPEPAR     = SNGL(DARRAY(1))
         SIMNAME_SHAPEPAR = 'SIM_DM15'
      ENDIF

      CALL FETCH_SNDATA_WRAPPER("SIM_SALT2x1", ONE, STRING, DARRAY, OPT)
      IF ( DARRAY(1) > -8.0 ) THEN
         SIM_SHAPEPAR     = SNGL(DARRAY(1))
         SIMNAME_SHAPEPAR = 'SIM_x1'
      ENDIF

c - - - -  filter dependent keys  - - - - -

      CALL RDHEAD_FILTERLOOP("SIM_PEAKMAG",  SIM_PEAKMAG, OPT)
      CALL RDHEAD_FILTERLOOP("SIM_EXPOSURE", SIM_EXPOSURE_TIME, OPT)
      CALL RDHEAD_FILTERLOOP("SIM_TEMPLATEMAG", SIM_TEMPLATEMAG, OPT) ! 9.20.2021


c - - -  model params: SIMSED, LCLIB, etc   - - - -

      DO ipar = 1, NPAR_SIMSED
         KEY  = SIMSED_KEYWORD(ipar)
         CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
         SIMSED_PARVAL(ipar) = SNGL(DARRAY(1))
      ENDDO


      DO ipar = 1, NPAR_PySEDMODEL
         KEY  = PySEDMODEL_KEYWORD(ipar)
         CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
         PySEDMODEL_PARVAL(ipar) = SNGL(DARRAY(1))
      ENDDO

      DO ipar = 1, NPAR_LCLIB
         KEY = LCLIB_KEYWORD(ipar)
         CALL FETCH_SNDATA_WRAPPER(KEY, ONE, STRING, DARRAY, OPT)
         LCLIB_PARVAL(ipar) = SNGL(DARRAY(1))
      ENDDO

      RETURN
      END    ! end RDHEAD_SIM_SNANA


C ===========================================
CDECK  ID>,  RDOBS_DRIVER. 
      SUBROUTINE RDOBS_DRIVER()

C Created Feb 11 2021
C Read event (FITS or TEXT format) and transfer epoch-dependent
c information from SNDATA C-struct to fortran variables.
c
c Jun 7 2021: abort on undefined filter

      IMPLICIT NONE
cc      INTEGER  ISN    ! (I) sparse SN index

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FITSCOM. inserted below by ypatchy. 

c define external C functions to read from fits files

c max length of catenated strings from all epochs;
c e.g., FIELD
c Aug 31 2023: 40k -> 80k
c Nov 16 2023: 80k -> 160k

      INTEGER MXLEN_EPSTRING
      PARAMETER (MXLEN_EPSTRING = 160000 )

      INTEGER
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR  ! read string
     &  ,RD_SNFITSIO_INT  ! read int
     &  ,RD_SNFITSIO_SHT  ! read short int
     &  ,RD_SNFITSIO_FLT  ! read float
     &  ,RD_SNFITSIO_DBL  ! read double

      EXTERNAL
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR
     &  ,RD_SNFITSIO_INT
     &  ,RD_SNFITSIO_SHT
     &  ,RD_SNFITSIO_FLT
     &  ,RD_SNFITSIO_DBL
     &  ,SET_RDMASK_SNFITSIO ! void
     &  ,RD_SNFITSIO_CLOSE   ! void function

c Define index-lookup arrays used for faster reading of fits files
      INTEGER MXFITSPAR
      PARAMETER ( MXFITSPAR = 400 )

      INTEGER
     &   INDXFITS_HEAD(MXFITSPAR)    ! used in RDSNFITS_HEAD
     &  ,INDXFITS_EPCUTS(MXFITSPAR)  ! used in RDSNFITS_EPCUTS
     &  ,INDXFITS_PHOT(MXFITSPAR)    ! used in RDSNFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,SNFITSIO_CODE_IVERSION     ! FITSIO version used to write data

c defin epoch mask for which

      INTEGER
     &   EPOCH_RDMASK_SNFITSIO(MXEPOCH)  ! epochs to keep/reject

c define long fits-string returned by RD_SNFITSIO_STR
      CHARACTER STRFITS*(MXLEN_EPSTRING)

      COMMON / FITSCOM /  SNFITSIO_CODE_IVERSION
     &  ,INDXFITS_HEAD, INDXFITS_EPCUTS, INDXFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,EPOCH_RDMASK_SNFITSIO, STRFITS



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      REAL*8 MJD_SAFETEY
      PARAMETER ( MJD_SAFETEY = 10.0 ) ! extra margin for MJD window

      INTEGER OPT, NOBS_STORE, o, LENTMP, IFILT, IFILT_OBS
      REAL*8 DARRAY(MXEPOCH), MJD_WINDOW(2), MJD
      REAL   z, z1, TOBS_MIN, TOBS_MAX
      CHARACTER STRING*12, FNAM*14, CFILT*2

      INTEGER  SELECT_MJD_SNDATA
      EXTERNAL SELECT_MJD_SNDATA

C ---------- BEGIN --------

      FNAM = 'RDOBS_DRIVER'

c set MJD window for copy SNDATA obs
      MJD_WINDOW(1) = 0.0;   MJD_WINDOW(2) = 1.0E6  ! default

c check to refine window around approx peakmjd
      if ( SNLC_SEARCH_PEAKMJD > 40000.0 ) then
         z  = SNLC_REDSHIFT
         z1 = 1.0 + z ;
         if ( z < 0.0 ) z1 = 1.0 + CUTWIN_REDSHIFT(2)
         TOBS_MIN = CUTWIN_TREST(1)*z1  ! note this is usually negative
         TOBS_MAX = CUTWIN_TREST(2)*z1  ! usually positive
         MJD_WINDOW(1) = SNLC_SEARCH_PEAKMJD + TOBS_MIN - MJD_SAFETEY
         MJD_WINDOW(2) = SNLC_SEARCH_PEAKMJD + TOBS_MAX + MJD_SAFETEY
      endif

      NOBS_STORE = SELECT_MJD_SNDATA(MJD_WINDOW)  ! C function

      if ( NOBS_STORE > MXEPOCH ) then
         write(C1ERR,660) NOBS_STORE, MXEPOCH
660      format('NOBS_STORE = ', I6, ' exceeds MXEPOCH=', I6)
         C2ERR = 'Need to increase MXEPOCH in snana.car'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

      ISNLC_NEWMJD_STORE = NOBS_STORE  ! store in global
      ISNLC_NEPOCH_STORE = NOBS_STORE

c - - - - - - - - - - -
c fetch SNDATA values and load fortran globals

      OPT = OPTMASK_SNDATA_OBS
c     &    + OPTMASK_SNDATA_DUMP

      DARRAY(1) = -999.0 ;      STRING = ''

      CALL FETCH_SNDATA_WRAPPER("MJD",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC8_MJD(o) = DARRAY(o);  ENDDO

      CALL FETCH_SNDATA_WRAPPER("BAND",
     &      NOBS_STORE, STRFITS, DARRAY, OPT)
      CALL UNPACK_SNFITSIO_STR(NOBS_STORE, "FLT", STRFITS)

      CALL FETCH_SNDATA_WRAPPER("CCDNUM",
     &        NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; ISNLC_CCDNUM(o)=int(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("IMGNUM",
     &        NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; ISNLC_IMGNUM(o)=int(DARRAY(o)); ENDDO


      CALL FETCH_SNDATA_WRAPPER("FIELD",
     &      NOBS_STORE, STRFITS, DARRAY, OPT)
      CALL UNPACK_SNFITSIO_STR(NOBS_STORE, "FIELD", STRFITS)

      CALL FETCH_SNDATA_WRAPPER("PHOTFLAG",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; ISNLC_PHOTFLAG(o)=int(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("PHOTPROB",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_PHOTPROB(o)=SNGL(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("FLUXCAL",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_FLUXCAL(o)=SNGL(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("FLUXCALERR",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_FLUXCAL_ERRTOT(o)=SNGL(DARRAY(o)); ENDDO

c - - - -
      UNIT_PSF_NEA = .FALSE.
      CALL FETCH_SNDATA_WRAPPER("PSF_NEA",
     &     NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE
         SNLC_PSF_NEA(o)=SNGL(DARRAY(o))
         if ( SNLC_PSF_NEA(o) > 0.0 ) UNIT_PSF_NEA = .true.
      ENDDO

      IF ( .NOT. UNIT_PSF_NEA ) THEN
         CALL FETCH_SNDATA_WRAPPER("PSF_SIG1",
     &        NOBS_STORE, STRING, DARRAY, OPT)
         DO o=1,NOBS_STORE; SNLC_PSF_SIG1(o)=SNGL(DARRAY(o)); ENDDO

         CALL FETCH_SNDATA_WRAPPER("PSF_SIG2",
     &        NOBS_STORE, STRING, DARRAY, OPT)
         DO o=1,NOBS_STORE; SNLC_PSF_SIG2(o)=SNGL(DARRAY(o)); ENDDO

         CALL FETCH_SNDATA_WRAPPER("PSF_RATIO",
     &        NOBS_STORE, STRING, DARRAY, OPT)
         DO o=1,NOBS_STORE; SNLC_PSF_RATIO(o)=SNGL(DARRAY(o)); ENDDO
      ENDIF
c - - - - -

      CALL FETCH_SNDATA_WRAPPER("SKY_SIG",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_SKYSIG(o)=SNGL(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("SKY_SIG_T",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_SKYSIG_T(o)=SNGL(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("ZEROPT",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_ZEROPT(o)=SNGL(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("ZEROPT_ERR",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_ZEROPT_ERR(o)=SNGL(DARRAY(o)); ENDDO

      CALL FETCH_SNDATA_WRAPPER("GAIN",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SNLC_GAIN(o)=SNGL(DARRAY(o)); ENDDO

      IF ( SNLC_NXPIX > 0.0 ) THEN
         CALL FETCH_SNDATA_WRAPPER("XPIX",
     &        NOBS_STORE, STRING, DARRAY, OPT)
         DO o=1,NOBS_STORE; SNLC_XPIX(o)=SNGL(DARRAY(o)); ENDDO

         CALL FETCH_SNDATA_WRAPPER("YPIX",
     &        NOBS_STORE, STRING, DARRAY, OPT)
         DO o=1,NOBS_STORE; SNLC_YPIX(o)=SNGL(DARRAY(o)); ENDDO
      ENDIF

c read optional variables for Atmos/DCR (Jul 2023)
      FOUND_ATMOS = .FALSE.
      CALL FETCH_SNDATA_WRAPPER("AIRMASS",
     &        NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE
          SNLC_AIRMASS(o)=SNGL(DARRAY(o))
          if ( SNLC_AIRMASS(o) > .9 ) FOUND_ATMOS = .true.
      ENDDO

      IF ( FOUND_ATMOS ) THEN
        CALL FETCH_SNDATA_WRAPPER("dRA",
     &        NOBS_STORE, STRING, DARRAY, OPT)
        DO o=1,NOBS_STORE; SNLC_dRA(o)=SNGL(DARRAY(o)); ENDDO

        CALL FETCH_SNDATA_WRAPPER("dDEC",
     &          NOBS_STORE, STRING, DARRAY, OPT)
        DO o=1,NOBS_STORE; SNLC_dDEC(o)=SNGL(DARRAY(o)); ENDDO
      ENDIF


c ----------------------------------------------
c ----------- SIM QUANTITIES BELOW -------------
c ----------------------------------------------

      if ( .NOT. ISJOB_SIM ) GOTO 800

c read SIM_MAGOBS for SNANA sim or FAKES ...

      CALL FETCH_SNDATA_WRAPPER("SIM_MAGOBS",
     &      NOBS_STORE, STRING, DARRAY, OPT)
      DO o=1,NOBS_STORE; SIM_EPMAGOBS(o)=SNGL(DARRAY(o)); ENDDO

c the rest is for SNANA sim only ...

      if ( .NOT. LSIM_SNANA ) GOTO 800

      LENTMP = INDEX(SIMNAME_SNRMON,' ') - 1
      IF ( LENTMP > 2 ) THEN
         CALL FETCH_SNDATA_WRAPPER(SIMNAME_SNRMON,
     &        NOBS_STORE, STRING, DARRAY, OPT)
         DO o=1,NOBS_STORE; SIM_EPSNRMON(o)=SNGL(DARRAY(o)); ENDDO
      ENDIF

c ---------------------------------
 800  CONTINUE

c compute a few misc variables related to input data;
c these are essentially change of units.

      DO o = 1, NOBS_STORE
        CALL SET_EPVAR_MISC(o)   ! set SNLC_ZP (ADU or Npe) and PSF_FWHM

        ISNLC_EPOCH_RANGE_NEWMJD(1,o) = o
        ISNLC_EPOCH_RANGE_NEWMJD(2,o) = o

        IFILT_OBS = ISNLC_IFILT_OBS(o)
        IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)

        IF ( IFILT < 0 ) THEN
           MJD = SNLC8_MJD(o)
           cfilt  = filtdef_string(ifilt_obs:ifilt_obs)
           write(c1err,61) IFILT_OBS, CFILT, SNLC_CCID(1:ISNLC_LENCCID)
61         format('Invalid IFILT_OBS=',I3, '(',A1,') for CID=',A)
           write(c2err,62) MJD
62         format('Check FILTERS key and MJD=', F9.3)
           CALL MADABORT(FNAM, c1err,c2err)
        ENDIF

        ISNLC_NEPOCH_FILT(ifilt) =
     &       ISNLC_NEPOCH_FILT(ifilt) + 1

c        print*,' xxx o, ifilt, ifilt_obs = ',
c     &        o, ifilt, ifilt_obs
      ENDDO

c Since SET_PEAKMJD has not been called [yet],
c apply all epoch cuts EXCEPT for Trest.

      CALL SELECT_EPOCH_DRIVER(1) ! 1 -> all obs/epoch cuts EXCEPT for Trest

      RETURN
      END       ! end RDOBS_DRIVER


C ===========================================
CDECK  ID>,  RDSPEC_DRIVER. 
      SUBROUTINE RDSPEC_DRIVER(ISPEC)

c
C Created Feb 17 2021
C Read spectra (FITS or TEXT format) and transfer
C information from GENSPEC C-struct to fortran variables.
C
C ISPEC = 0 -> read header info
C ISPEC > 0 -> read wave-dependent arrays for ISPEC

      IMPLICIT NONE

      INTEGER ISPEC  ! (I)

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


      INTEGER    OPT, NBLAM, I
      REAL*8     DVAL(10)
      CHARACTER  FNAM*14

C ------------ BEGIN ----------

      FNAM = 'RDSPEC_DRIVER'
      OPT = 0
c     &    + OPTMASK_SNDATA_DUMP

      IF ( ISPEC == 0 ) THEN
         CALL FETCH_GENSPEC_WRAPPER("NSPECTRA", -9, DVAL, OPT)
         NSPECTRUM = INT(DVAL(1))

         IF ( NSPECTRUM .LE. 0 ) RETURN

         IF ( NSPECTRUM > MXSPECTRUM .or. NSPECTRUM < 0 ) THEN
            write(c1err, '(A,I3)' ) 'Invalid NSPECTRUM = ', NSPECTRUM
            write(c2err, '(A,I3)' ) 'MXSPECTRUM = ', MXSPECTRUM
            CALL MADABORT(FNAM, c1err,c2err)
         ENDIF


c load up all the spec-header info now; the big LAM-dependent
c arrays are loaded later with ISPEC > 0.

         DO I = 1, NSPECTRUM
            CALL FETCH_GENSPEC_WRAPPER("NBLAM", I, DVAL, OPT)
            NLAMBIN_SPECTRUM(I) = INT(DVAL(1))
            NBLAM = NLAMBIN_SPECTRUM(I)

            if ( NBLAM > MXLAM_SPECTRUM .or. NBLAM < 0 ) then
               write(c1err,'(A,I8)') 'Invalid NLAMBIN = ', NBLAM
               write(c2err,'(A,I8)') 'MXLAM_SPECTRUM=',MXLAM_SPECTRUM
               CALL MADABORT(FNAM, c1err,c2err)
            endif

            CALL FETCH_GENSPEC_WRAPPER("ID", I, DVAL, OPT)
            ID_SPECTRUM(I)    = INT(DVAL(1))

            CALL FETCH_GENSPEC_WRAPPER("MJD", I, DVAL, OPT)
            MJD_SPECTRUM(I)    = DVAL(1)
            TOBS_SPECTRUM(I)   = DVAL(1) - SNLC_SEARCH_PEAKMJD

            CALL FETCH_GENSPEC_WRAPPER("TEXPOSE", I,
     &           TEXPOSE_SPECTRUM(I), OPT)
         ENDDO

         RETURN
      ENDIF

c - - - - - - -  -
c retreive SPECTRUM for ISPEC.
c wave-dependent arrays
      CALL FETCH_GENSPEC_WRAPPER("LAMMIN", ISPEC,
     &     LAMMIN_SPECTRUM, OPT)
      CALL FETCH_GENSPEC_WRAPPER("LAMMAX", ISPEC,
     &     LAMMAX_SPECTRUM, OPT)

      CALL FETCH_GENSPEC_WRAPPER("FLAM", ISPEC,
     &     FLAM_SPECTRUM, OPT)
      CALL FETCH_GENSPEC_WRAPPER("FLAMERR", ISPEC,
     &     FLAMERR_SPECTRUM, OPT)

      IF (  LSIM_SNANA ) THEN
         CALL FETCH_GENSPEC_WRAPPER("SIM_FLAM", ISPEC,
     &        SIM_FLAM_SPECTRUM, OPT)
      ENDIF

      RETURN
      END     ! end RDSPEC_DRIVER


C ==============================================
CDECK  ID>,  LDONE_CIDLIST. 
      LOGICAL FUNCTION LDONE_CIDLIST()

c Jun 2011:
c Returns TRUE if all CID in the list have been processed;
c allows parsing function to stop early.
c
c May 18, 2012: return FALSE if interp-option is set
c Jun 25, 2019: check MXEVT_PROCESS
c Oct 12, 2021: check MXEVT_CUTS
c -----------
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


      LOGICAL LNCID

c ------------- BEGIN --------------

      LDONE_CIDLIST = .FALSE.  ! default

      if ( N_SNLC_PROC .GE. MXEVT_PROCESS ) then
         LDONE_CIDLIST = .TRUE.
         RETURN
      endif

      if ( N_SNLC_CUTS .GE. MXEVT_CUTS ) then
         LDONE_CIDLIST = .TRUE.
         RETURN
      endif

c if CUTWIN_CID is set then return FALSE
      if ( cutwin_cid(1) .GT. 0 ) RETURN
      if ( cutwin_cid(2) .GT. 0 ) RETURN

      if ( SNCID_LIST_FILE .NE. ' ' ) RETURN ! Nov 2013

c return FALSE if interp-option is set but not finished

      if ( N_INTERP_MJDLIST .GT. 0 .and.
     &     N_INTERP_MJDLIST_DONE .LT. N_INTERP_MJDLIST ) THEN
           LDONE_CIDLIST = .FALSE.
           RETURN
      endif

      LNCID = NACCEPT_CID .EQ. (NCID_LIST + NCCID_LIST)
      IF ( LNCID ) THEN
        LDONE_CIDLIST = .TRUE.
      ENDIF

      RETURN
      END       ! END OF LDONE_CIDLIST


C =======================
CDECK  ID>,  PRSPRVKEY. 
      SUBROUTINE PARSE_PRIVATE_KEYWORD(CWORD, IVAR_PRIVATE)

c For input CWORD = 'PRIVATE($VARNAME)', strip out the $VARNAME
c and load PRIVATE_VARNAME(IVAR_PRIVATE) = $VARNAME
c
c Apr 27 2021: check veto option with VARNAME != VALUE
c
      IMPLICIT NONE

c input args
      CHARACTER CWORD*60     ! (I) text string to parse
      INTEGER IVAR_PRIVATE   ! (I) PRIVATE parameter index

c local args

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



      INTEGER J1, J2, LK, IVAR, LEN_NAME, NMATCH, icut
      INTEGER NWD, LWD1, LWD2, LWD3, MSKOPT
      CHARACTER VARNAME*60, STR*(MXCHAR_CUTNAME), CUTSTRING*30
      CHARACTER CWD1*60, CWD2*60, CWD3*60, FNAM*30

      LOGICAL LCUTWIN
      REAL*8 CUTWIN(2)

c function
      INTEGER NMATCH_PRIVATE

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C --------------- BEGIN --------------

      FNAM = 'PARSE_PRIVATE_KEYWORD'

c store keyword WITHOUT the ':' on the end.
      LK = INDEX( CWORD , ':' ) - 1
      IF ( LK .LT. 0 ) LK = INDEX(CWORD,' ' ) - 1
      PRIVATE_KEYWORD(IVAR_PRIVATE) = CWORD(1:LK)

c now extract the parameter name from inside the ().
c For example, if KEYWORD = 'PRIVATE(BLA):'
c then the VARNAME is 'BLA'.

      J1 = INDEX( CWORD , '(' )
      J2 = INDEX( CWORD , ')' )

      IF ( J1 .EQ. 0 .or. J2 .EQ. 0 ) THEN
         c1err = 'Invalid PRIVATE_KEYWORD = ' // CWORD(1:LK)
         c2err = 'Expecting to find key-string  PRIVATE(PARNAME)'
         CALL MADABORT("PARSE_PRIVATE_KEYWORD", c1err,c2err)
      ENDIF


      VARNAME = CWORD(j1+1:j2-1)
      LEN_NAME = INDEX(VARNAME // ' ', ' ' ) - 1

c load parameter name into global variable

      PRIVATE_VARNAME(IVAR_PRIVATE) = VARNAME

c ----------------------------------------------------
c make sure that this NAME has not already been used

      NMATCH = NMATCH_PRIVATE(VARNAME,IVAR)

      IF ( NMATCH > 1 ) then
         c1err = 'found duplicate PRIVATE variable: '
     &                // VARNAME(1:LEN_NAME)
         c2err = 'Check PRIVATE(XXX) keys'
         CALL MADABORT("PARSE_PRIVATE_KEYWORD", c1err,c2err)
      ENDIF

c -------- check for cut on private var (Nov 4 2014) ---------
c Allow two syntaxes:
c  VARNAME CUTMIN CUTMAX    or
c  VARNAME != VETO_VALUE

      LCUTWIN = .FALSE.
      CUTSTRING = ''
      DO 400 icut = 1, MXCUT_PRIVATE

         STR = PRIVATE_CUTWIN_STRING(icut)  ! 'VARNAME CUTMIN CUTMAX'
         if ( STR .EQ. '' ) GOTO 400

c        skip if already found
         CUTWIN(2) = PRIVATE_CUTWIN(2,IVAR_PRIVATE)
         if ( CUTWIN(2) < .99*CUTVAL_OPEN ) GOTO 400

c break up string into pieces
         MSKOPT = MSKOPT_PARSE_WORDS_STRING
         NWD = STORE_PARSE_WORDS(MSKOPT,STR//' '//char(0),
     &        FNAM//char(0), 60, 30)
         call get_PARSE_WORD_fortran(1,CWD1,LWD1)

         if ( VARNAME .EQ. CWD1 ) then
            NCUT_PRIVATE = NCUT_PRIVATE + 1
            LCUTWIN = .TRUE.

            call get_PARSE_WORD_fortran(2,CWD2,LWD2)
            call get_PARSE_WORD_fortran(3,CWD3,LWD3)

            if ( CWD2(1:2) .EQ. '!=' ) then
               read(CWD3,*) CUTWIN(1)
               CUTWIN(2) = CUTWIN(1)
               USE_PRIVATE_CUTWIN(IVAR_PRIVATE) = -1 ! veto flag
               write(CUTSTRING,446) CUTWIN(1)
            else
               read(CWD2,*) CUTWIN(1)
               read(CWD3,*) CUTWIN(2)
               USE_PRIVATE_CUTWIN(IVAR_PRIVATE) = 1 ! normal cutwin
               write(CUTSTRING,444) CUTWIN
            endif

            PRIVATE_CUTWIN(1,IVAR_PRIVATE) = CUTWIN(1)
            PRIVATE_CUTWIN(2,IVAR_PRIVATE) = CUTWIN(2)

 444        format('CUT: ',G9.3,' to ', G9.3)
 446        format('VETO: ', G9.3)
         endif
 400  CONTINUE

c ----------------------------
c print one-line summary

      IF ( .NOT. DO_GETINFO ) THEN
        write(6,500) CWORD(1:LK), CUTSTRING
 500    format(T5,'Found ', A, T50,A)
        call flush(6)
      ENDIF

      RETURN
      END  ! end  PARSE_PRIVATE_KEYWORD

C ===============================
CDECK  ID>,  NMAPRIV. 
      INTEGER FUNCTION NMATCH_PRIVATE(NAME,IVAR_PRIVATE)

c
c Return number of NAME matches ; check both
c PRIVATE_VARNAME and PRIVATE_KEYWORD.
c Also returns IVAR_PRIVATE that is valid if NMATCH=1

      IMPLICIT  NONE
      CHARACTER NAME*(*)
      INTEGER   IVAR_PRIVATE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



      INTEGER
     &   IVAR
     &  ,LEN_TMP, LEN_NAME
     &  ,NMATCH

      CHARACTER TMPNAME*60

C --------------- BEGIN --------------

      IVAR_PRIVATE   = -9
      NMATCH_PRIVATE =  0
      NMATCH         =  0
      LEN_NAME       = INDEX(NAME//' ' , ' ') - 1

      DO 30 IVAR = 1, NVAR_PRIVATE
        TMPNAME  = PRIVATE_VARNAME(IVAR)
        LEN_TMP  = INDEX(TMPNAME,' ') - 1
        IF ( LEN_TMP .NE. LEN_NAME ) goto 30

        if ( NAME(1:LEN_NAME) .EQ. TMPNAME(1:LEN_NAME) ) then
           IVAR_PRIVATE = IVAR
           NMATCH = NMATCH + 1
        endif
30    CONTINUE

c check the full name 'PRIVATE($VARNAME)'

      DO 32 IVAR = 1, NVAR_PRIVATE
        TMPNAME  = PRIVATE_KEYWORD(IVAR)
        LEN_TMP  = INDEX(TMPNAME,' ') - 1
        IF ( LEN_TMP .NE. LEN_NAME ) goto 32

        if ( NAME(1:LEN_NAME) .EQ. TMPNAME(1:LEN_NAME) ) then
           IVAR_PRIVATE = IVAR
           NMATCH = NMATCH + 1
        endif

32    CONTINUE


      NMATCH_PRIVATE = NMATCH

      RETURN
      END


C END_DATA_IO

C ==========================================
CDECK  ID>,  PROCESS_DATA. 
      SUBROUTINE PROCESS_DATA_VERSION(IVERS)

c Created Feb 16 2021 as part of I/O refactor.
c Called from MAIN to read & ananlyze events.

      IMPLICIT NONE

      INTEGER IVERS  ! (I) version index to process


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C --------------- BEGIN -------------

      CALL GETINFO_PHOTOMETRY(ivers)

      CALL READ_EPIGNORE_FILE(ivers)

      CALL EXEC_READ_DATA(ivers,OPTMASK_SNDATA_ALL)

      RETURN
      END   ! end PROCESS_DATA_VERSION

C ==========================================
CDECK  ID>,  PARSE_SNANA_ARGS. 
      SUBROUTINE PARSE_SNANA_ARGS()
c
c Nov 08, 2012
c Parse command-line arguments and store in LINE_ARGS array.
c (code moved from main)
c
c May 2019: check option to call DUMP_SNANA_VERSION
c Dec 2020: abort on ARG string length too long.
c Aug 2020: of no args, call function to print help menu
c Dec 2022: get SNANA_VERSION here to print it after full command

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      INTEGER i, LL, LL_SNANA, istat
      CHARACTER ARG1*(MXCHAR_ARG), ARG2*(MXCHAR_ARG)
      CHARACTER FNAM*20, COMMAND*2000, CODE_FILENAME*40
      CHARACTER CMD_HELP*100, CMD_SNANA_HELP*100

      EXTERNAL GET_SNANA_VERSION

C ------------------- BEGIN ---------------

      FNAM = 'PARSE_SNANA_ARGS'

      NLINE_ARGS = IARGC()  ! intrinsic fortran function

c get SNANA version from C function
      call GET_SNANA_VERSION(SNANA_VERSION,40)
      LL_SNANA = index(SNANA_VERSION, char(0) ) - 1
      SNANA_VERSION(LL_SNANA+1:LL_SNANA+2) = ' '

c - - - - - - - - - - - - - - - - - -
c Aug 2022: if there are no arguments, print help menu
      IF ( NLINE_ARGS == 0 ) THEN

c  always print help for &SNLCINP base code inputs
         CMD_SNANA_HELP = 'help_inputs_fortran.py ' // 'snana.car'
         CALL SYSTEM(CMD_SNANA_HELP)

          CODE_FILENAME = 'snlc_fit.car'

	 if ( CODE_FILENAME .NE. '' )  then
            CMD_HELP = 'help_inputs_fortran.py ' // CODE_FILENAME
            CALL SYSTEM(CMD_HELP)
         endif
         STOP
      ENDIF
c - - - - - - - - - - - - - - - - - -

      IF ( NLINE_ARGS .GT. MXLINE_ARGS ) THEN
         write(c1err,661) NLINE_ARGS
         write(c2err,662) MXLINE_ARGS
661      format(I3,' command-line arguments exceeds bound of')
662      format('MXLINE_ARGS = ', I4)
         CALL  MADABORT("PARSE_SNANA_ARGS", C1ERR, C2ERR)
      ENDIF


      CALL GET_COMMAND(COMMAND,LL, istat)

c abort on bad string length
      DO i = 1, NLINE_ARGS
        CALL GETARG(i, ARG1)

        if ( ARG1(MXCHAR_ARG:MXCHAR_ARG) .NE. ' ' ) then
           CALL PRINT_PREABORT_BANNER(FNAM//char(0),20)
           print*,'  ARG = ', ARG1
           c1err = 'String length too long for command-line ARG ' //
     &             ' (see above)'
           write(c2err, '(A,I6)' ) 'MXCHAR_ARG = ', MXCHAR_ARG
           CALL MADABORT(FNAM, c1err, c2err)
        endif

        USE_LINE_ARGS(i) = .FALSE.
      ENDDO

      CALL GETARG(1, ARG1)
      CALL GETARG(2, ARG2)

c check option to dump SNANA version and SNANA_DIR
c (for SNANA_CodeTests.py)
c    snana.exe --snana_version

      IF ( ARG1 .EQ. '--SNANA_VERSION' .or.
     &     ARG1 .EQ. '--snana_version'  ) THEN
         CALL DUMP_SNANA_VERSION()
      ELSE
         print*,' Full command:  ', COMMAND(1:LL)
         print*,' '
         print*,' SNANA_VERSION: ', SNANA_VERSION(1:LL_SNANA)
         print*,' '

      ENDIF

c snana.exe GETINFO <VERSION_PHOTOMETRY>
      DO_GETINFO = .FALSE.
      IF ( ARG1 .EQ. 'GETINFO' ) THEN
         CALL DUMP_INFO_VERSION_PHOTOMETRY(ARG2)
      ENDIF

      RETURN
      END      ! end PARSE_SNANA_ARGS


C ==================================
CDECK  ID>,  DUMP_SNANA_VERSION. 
      SUBROUTINE DUMP_SNANA_VERSION()

c Created May 2019
c Dump SNANA version and SNANA_DIR, then quit.

      IMPLICIT NONE
      INTEGER LL
      CHARACTER SNANA_VERSION*40, SNANA_DIR*200

      call GET_SNANA_VERSION(SNANA_VERSION,LL)
      LL = index(SNANA_VERSION, char(0) ) - 1
      print*,'SNANA_VERSION: ', SNANA_VERSION(1:LL)

      CALL GETENV ( 'SNANA_DIR', SNANA_DIR )
      LL = INDEX(SNANA_DIR,' ') - 1
      print*,'SNANA_DIR: ', SNANA_DIR(1:LL)

      CALL EXIT(0)

      RETURN
      END

C ======================================
CDECK  ID>,  DUMP_INFO_VER_PHOT. 
      SUBROUTINE DUMP_INFO_VERSION_PHOTOMETRY(VERSION_ARG)

c Created Aug 29 2019
c dump path and format for VERSION_PHOTOMETRY; then quit.
c
c Apr 2021: pass VERSION_ARG and dump more info
c Jan 10 2022: write NVAR_PRIVATE

      IMPLICIT NONE
      CHARACTER VERSION_ARG*(*)  ! VERSION or PATH/VERSION


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



c local var
      CHARACTER VERSION*(MXCHAR_FILENAME), COMMENT*40
      INTEGER IERR, LEN, JSLASH
C -------------- BEGIN ------------

      DO_GETINFO = .TRUE.

c if VERSION_ARG has full path, split it into PRIVATE_DATA_PATH and
c VERSION_PHOTOMETRY

      LEN     = INDEX(VERSION_ARG,' ') -1
      JSLASH  = INDEX(VERSION_ARG, '/', BACK = .True. )
      IF ( JSLASH > 1 ) THEN
         VERSION_PHOTOMETRY(1) = VERSION_ARG(JSLASH+1:LEN)
         PRIVATE_DATA_PATH     = VERSION_ARG(1:JSLASH-1)
      ELSE
         VERSION_PHOTOMETRY(1) = VERSION_ARG(1:LEN)
      ENDIF

      CALL INIT_SNVAR()
      CALL CHECK_FORMAT()
      CALL INIT_READ_DATA()

c - - - - - - - - - - - -
      print*,' '
      print*,' '

      VERSION = VERSION_PHOTOMETRY(1)
      LEN     = INDEX(VERSION,' ')-1
      write(6,20) 'VERSION:', VERSION(1:LEN), ''

      LEN = INDEX(SNDATA_PATH,' ') - 1
      write(6,20) 'SNDATA_PATH:', SNDATA_PATH(1:LEN), ' '

      LEN = INDEX(SNLIST_FILE,' ') - 1
      write(6,20) 'LIST_FILE:  ', SNLIST_FILE(1:LEN), ' '

      LEN = INDEX(SNREADME_FILE(1),' ') - 1
      write(6,20) 'README_FILE:', SNREADME_FILE(1)(1:LEN), ' '

 20   format(A, 2x, A,  3x, A)
 21   format(A, 2x, I8, 3x, A)
c - - - - - - - - - - - -
      if ( FORMAT_TEXT ) then
         write(6,20) 'FORMAT: ', 'TEXT',
     &         '# one TEXT file per SN'
      else
         write(6,20) 'FORMAT: ', 'FITS',
     &         '# FITS-HEADER and FITS-PHOT file'
      endif

      LEN = INDEX(SURVEY_NAME,' ') - 1
      write(6,20) 'SURVEY: ', SURVEY_NAME(1:LEN), ' '

      write(6,20) 'FILTERS:', SURVEY_FILTERS(1:NFILTDEF_SURVEY), ' '

      write(6,21) 'NEVENT: ',  N_SNLC_READ(1), ' '

      COMMENT = ''
      IF ( DATATYPE == 'SIM_MAGOBS' ) THEN
         COMMENT='# Fakes overlaid on images'
      ENDIF
      write(6,20) 'DATATYPE: ',  DATATYPE, COMMENT

      write(6,21) 'NVAR_PRIVATE: ',  NVAR_PRIVATE, ' '

      CALL FLUSH(6)
      CALL EXIT(0)

      RETURN
      END      ! end DUMP_INFO_VERSION_PHOTOMETRY

C ==================================
CDECK  ID>,  RDSNNML. 
      SUBROUTINE RDSNNML(IERR)
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c
c Jan 5 2016: if NMLFILE = 'NOFILE', then skip reading file
c             and jump to SNLCINP_OVERRIDE. Allows running snana
c             with only command-line options and no nml file.
c
c Feb 27 2018: check CUTWIN_ZP
c Apr 07 2022; use function VALIDFILENAME
c
c ---------------

      INTEGER IERR   ! 0=>OK,  else error

c local ars

      integer i, ifilt, LL, ipar, NZPCUT, bit
      character nmlfile_default*40, FNAM*8

c function
      INTEGER PARSE_NML_STRINGLIST
      LOGICAL VALIDFILENAME

C -------------- BEGIN -----------
      IERR = 0

      CALL PRBANNER ( " READ SNLCINP NAMELIST. " )

      FNAM = 'RDSNNML'

c ----------------------------------------
c set namelist defaults

      VERSION_PHOTOMETRY_WILDCARD = 'NULL'
      DO i = 1, MXVERS
        VERSION_PHOTOMETRY(i) = 'NULL'
      ENDDO
      VERSION_REFORMAT_FITS = 'NULL'
      VERSION_REFORMAT_TEXT = 'NULL'

      PRIVATE_DATA_PATH  = ' '
      FILTER_UPDATE_PATH = ' '
      OPT_YAML              = 0
      OPT_REFORMAT_SALT2    = 0
      OPT_REFORMAT_TEXT     = 0
      OPT_REFORMAT_FITS     = 0
      OPT_REFORMAT_SPECTRA  = 0
      REFORMAT_SAVE_BADEPOCHS  = .FALSE.
      REFORMAT_SPECTRA_INCLUDE = .FALSE.
      REFORMAT_SPECTRA_ONLY    = .FALSE.
      REFORMAT_PRIVATE         = .TRUE.
      REFORMAT_SIMTRUTH        = .TRUE.
      REFORMAT_KEYS     = 'NULL'

      NONSURVEY_FILTERS = ''
      SNRMAX_FILTERS    = ''  ! blank -> use all filters
      FILTER_REPLACE    = ''
      FILTLIST_LAMSHIFT = ''

      VPEC_ERR_OVERRIDE = 0.0

      JOBSPLIT(1) = 1
      JOBSPLIT(2) = 1

      JOBSPLIT_EXTERNAL(1) = 1
      JOBSPLIT_EXTERNAL(2) = 1

      SIM_PRESCALE   = 1.0
      OPTSIM_LCWIDTH = 0

      MNFIT_PKMJD_LOGFILE = 'MNFIT_PKMJD.LOG'

      SNMJD_LIST_FILE = ' '
      SNMJD_OUT_FILE  = ' '

      CUTWIN_MJD_EXCLUDE(1) = 0.0
      CUTWIN_MJD_EXCLUDE(2) = 0.0

      CUTWIN_MJD_INCLUDE(1) = -CUTVAL_OPEN
      CUTWIN_MJD_INCLUDE(2) = +CUTVAL_OPEN

      CUTWIN_SNR_NODETECT(1) = -CUTVAL_OPEN
      CUTWIN_SNR_NODETECT(2) = +CUTVAL_OPEN

      SNCUT_HOST_SBFLUX = ''
      SNCUT_SNRMAX = ''
      EPCUT_SNRMIN = ''
      EPCUT_SKYSIG = ''
      EPCUT_PSFSIG = ''

      CUTWIN_NFIELD(1) = 1.0
      CUTWIN_NFIELD(2) = 999.0

      CUTWIN_NFILT_SNRMAX(1) = 0.0
      CUTWIN_NFILT_SNRMAX(2) = 100.

      CUTWIN_NFILT_SNRMAX2(1) = 0.0
      CUTWIN_NFILT_SNRMAX2(2) = 100.

      CUTWIN_NFILT_TRESTMIN(1) =   1.
      CUTWIN_NFILT_TRESTMIN(2) = 100.
      CUTWIN_NFILT_TRESTMAX(1) =   1.
      CUTWIN_NFILT_TRESTMAX(2) = 100.
      CUTWIN_NFILT_TREST2(1)   =   1.
      CUTWIN_NFILT_TREST2(2)   = 100.

      CUTWIN_LAMREST(1)      =  2000.  ! Angstroms
      CUTWIN_LAMREST(2)      = 25000.
      CUTWIN_LAMOBS(1)       =  2000.
      CUTWIN_LAMOBS(2)       = 25000.

      CUTWIN_NBAND_THRESH(1) = -9.0   !  obsolete as of Nov 15 2019
      CUTWIN_NBAND_THRESH(2) = -9.0

      do ifilt = 1, MXFILT_OBS
         CUTWIN_SNRMIN_FILT(1,ifilt) = -CUTVAL_OPEN
         CUTWIN_SNRMIN_FILT(2,ifilt) = +CUTVAL_OPEN
      enddo

      CUTWIN_TREST_TRUEFLUX(1)  = 999.0 ! user input
      CUTWIN_TREST_TRUEFLUX(2)  = 999.0
      CUTWIN_TREST_TRUEFLUX2(1) = 0.9  ! logical cutwin
      CUTWIN_TREST_TRUEFLUX2(2) = 1.1

c Setting ignore file to 'NONE' => do not read any file.
c Setting INGORE file to 'DEFAULT' is a flag to read
c epochs-to-ignore from $SNDATA_ROOT/lcmerge/[version].IGNORE

      EPOCH_IGNORE_FILE = 'DEFAULT'
      OUT_EPOCH_IGNORE_FILE = ''

      KCOR_FILE    = 'NULL'
      OVERRIDE_RESTLAM_BOUNDARY = ''

      hfile_out         = ' '
      rootfile_out      = ' '
      textfile_prefix   = ' '
      MARZFILE_OUT      = ' '  ! May 2020

      SNCID_LIST_FILE   = ' '
      OPT_SNCID_LIST    = 0  ! default 0 => AND with other cuts

      MXEVT_PROCESS      = 999888777
      MXEVT_CUTS         = 999888777
      SIMLIB_OUT     = ''
      SIMLIB_OUTFILE = ''
      SIMLIB_ZPERR_LIST = ''
      OPT_SIMLIB_OUT    = 1
      SIMLIB_OUT_TMINFIX = 99999 ! large value -> not used

      NONLINEARITY_FILE = ''

      DO i = 1, MXLISTNML
         SNTYPE_LIST(i)    = 0
         SNTYPE_IGNORE(i)  = -9  ! note that type=0(no type) can be ignored
         CCDNUM_LIST(i)    = 0
         SNCID_LIST(i)     = 0
         SNCID_IGNORE(i)   = 0
         SIM_TEMPLATE_INDEX_LIST(i) = 0

         SNCCID_LIST(i)    = ''
         SNCCID_IGNORE(i)  = ''
         SNCCID_PLOT(i)    = ''

         SNFIELD_LIST(i)     = ''
         IDFIELD_LIST(i)     = -9
      ENDDO

c set default field to ALL
      SNFIELD_LIST(1)   = 'ALL'

      NSNTYPE_LIST = 0
      NCCDNUM_LIST = 0
      NSNTYPE_IGNORE = 0

      NIDFIELD_LIST = 0
      NCCID_LIST = 0
      NCID_LIST  = 0

      SNCID_IGNORE_FILE = ''

c set photometry-flag bits to reject;
c default is to reject nothing (accept everything)

      PHOTFLAG_MSKREJ(1) = -1  ! negative -> not set
      PHOTFLAG_MSKREJ(2) = 0
      PHOTFLAG_MSKREJ(3) = 0
      PHOTFLAG_MSKREJ(4) = 0
      PHOTFLAG_MSKREJ(5) = 0

      do i = 1, MXBIT_PHOTFLAG
         PHOTFLAG_BITLIST_REJECT(i) = -9 ! beware that 0 is valid bit
      enddo

      SNCID_IGNORE(1)    = 0

      MAGOBS_SHIFT_PRIMARY  = ''
      MAGOBS_SHIFT_ZP       = ''
      MAGREST_SHIFT_PRIMARY = ''
      MAGREST_SHIFT_ZP      = ''
      FILTER_LAMSHIFT       = ''

      DO i = 1, 3
        MAGOBS_SHIFT_PRIMARY_PARAMS(i) = 0.0
        MAGOBS_SHIFT_ZP_PARAMS(i)      = 0.0
      ENDDO

      FUDGE_FLUXCAL_OFFSET = ''
      FUDGE_FLUXCAL_ERROR  = ''
      FUDGE_FLUXCAL_ERRPIX = ''
      FUDGE_FLUXERR_SCALE  = ''
      FUDGE_MAG_ERROR      = ''
      FUDGE_MAG_COVERR     = ''
      FUDGE_HOSTNOISE_FILE = ''
      FLUXERRMODEL_FILE    = ''
      SIM_FLUXERRMODEL_FILE = ''
      FLUXERRMODEL_OPTMASK = 0
      MAGCOR_FILE          = ''
      SIM_MAGCOR_FILE      = ''

      MWEBV_SCALE    = 1.0
      MWEBV_SHIFT    = 0.0
      MWEBV_FORCE    = -9.0
      OPT_MWCOLORLAW = -9   ! use default if not specified in &SNLCINP
      OPT_MWEBV      = -9   ! idem
      RV_MWCOLORLAW  = -9.0 ! idem

      HOSTGAL_PHOTOZ_SHIFT = 0.0
      HOSTGAL_SPECZ_SHIFT  = 0.0
      REDSHIFT_FINAL_SHIFT = 0.0
      FLUXERRCALC_ZPTERR  = -9.9

      NFIT_ITERATION     = 0
      MINUIT_PRINT_LEVEL = -1  ! default is no MINUIT printing
      INTERP_OPT     = INTERP_LINEAR
      USE_MINOS      = .FALSE.  ! change from T to F, Jan 27 2017

      MXLC_FIT         = 999888777
      MXLC_PLOT        = 5    ! 100->5  (Apr 19 2022)
      NCCID_PLOT       = 0
      DTOBS_MODEL_PLOT = 2.0  ! 2 day binning
      MJDPERIOD_PLOT   = 0.0
      MJDSHIFT_PLOT    = 0.0

      OPT_SETPKMJD      = 0
      SNRCUT_SETPKMJD   =  5.0  ! only for FLUXMAX2 option (Fmax-clump)
      MJDWIN_SETPKMJD   = 60.0  ! only for FLUXMAX2 option (Fmax-clump)
      SHIFT_SETPKMJD    =  0.0  ! for systematic test only

      DEBUG_FLAG          =  0
      LDMP_SNFAIL         = .FALSE.
      LDMP_SNANA_VERSION  = .FALSE.
      LDMP_SATURATE       = .FALSE.

      LSIM_SEARCH_SPEC    = .FALSE.
      LSIM_SEARCH_ZHOST   = .FALSE.

      USESIM_SNIA      = .TRUE.
      USESIM_NONIA     = .TRUE.
      USESIM_TRUEFLUX  = .FALSE.

      LPROB_TRUEFLUX     = .FALSE.
      RESTORE_WRONG_VPEC = .FALSE.    ! Nov 3 2020
      RESTORE_OVERRIDE_ZBUG = .FALSE. ! Dec 12 2021
      RESTORE_MWEBV_ERR_BUG = .FALSE. ! Jul 2022
      REQUIRE_DOCANA     =  0       ! use integer to match sim usage

      USE_KCOR_REFACTOR = .TRUE.   ! permanently set, Dec 2 2022

      USE_HOSTGAL_PHOTOZ = .FALSE.
      USE_SNHOST_ZPHOT   = .FALSE.
      USE_MWCOR          = .FALSE.  ! apply MWCOR to fit-model

c by default do NOT check for multiseason activity (Oct 2014)
      MULTISEASON_TGAP               = 1.0E9
      MULTISEASON_NREJECT_OUTLIER    = 0
      MULTISEASON_CHI2RED_ACTIVE     = 5.0

      PHOTFLAG_DETECT   = 0
      PHOTFLAG_TRIGGER  = 0

      CUTWIN_NSEASON_ACTIVE(1) = -99.
      CUTWIN_NSEASON_ACTIVE(2) = +99.

      CUTWIN_CUTFLAG_REQEP(1) = 0.99
      CUTWIN_CUTFLAG_REQEP(2) = 1.01

c hard-wire cut on private cut-flag (Nov 4 2014)
      CUTWIN_CUTFLAG_PRIVATE(1) = 0.99
      CUTWIN_CUTFLAG_PRIVATE(2) = 1.01

      CUTWIN_CUTFLAG_SIMVAR(1) = 0.99
      CUTWIN_CUTFLAG_SIMVAR(2) = 1.01

c set reference cosmo params to defaults.
      H0_REF(1)   = H0_DEFAULT
      H0_REF(2)   = H0ERR_DEFAULT
      OMAT_REF(1) = OMAT_DEFAULT
      OMAT_REF(2) = OMATERR_DEFAULT
      OLAM_REF(1) = OLAM_DEFAULT
      OLAM_REF(2) = OLAMERR_DEFAULT
      ORAD_REF(1) = ORAD_DEFAULT
      ORAD_REF(2) = 0.0
      W0_REF(1)   = W0_DEFAULT
      W0_REF(2)   = W0ERR_DEFAULT
      DWDA_REF(1) = DWDA_DEFAULT
      DWDA_REF(2) = DWDAERR_DEFAULT

      zTOL_HELIO2CMB   = 0.02   ! tolerance on dzHELIO/zHELIO
      QUANTILE_ZERRMIN = 0.00   ! 0 -> always use quantiles

c set LTEST logicals to false.

      LTEST_KCOR    = .FALSE.
      LTEST_INTERP  = .FALSE.
      LTEST_U3BAND  = .FALSE.
      LTEST_MAG     = .FALSE.

      ABORT_ON_NOEPOCHS  = .TRUE.
      ABORT_ON_BADAVWARP = .TRUE.
      ABORT_ON_BADZ      = .TRUE.
      ABORT_ON_BADKCOR   = .TRUE.
      ABORT_ON_BADSURVEY = .TRUE.
      ABORT_ON_BADFILTER = .TRUE.
      ABORT_ON_MARGPDF0  = .TRUE.
      ABORT_ON_TRESTCUT  = .TRUE. ! for photo-z fits only
      ABORT_ON_DUPLCID   = .TRUE.
      ABORT_ON_DUPLMJD   = .FALSE.  ! Jun 2017
      ABORT_ON_NOPKMJD   = .TRUE.

      SNTABLE_LIST          = 'DEFAULT'  ! Sep 08 2014
      SNTABLE_FILTER_REMAP  = ''
      WRTABLEFILE_SIMVAR    = .TRUE.     ! Jul 17 2016
      WRTABLEFILE_ZPHOT     = .TRUE.     ! Mar 19 2018
      WRTABLEFILE_HOST_TEXT  = .FALSE.    ! May 23 2019
      WRTABLEFILE_HOST2_TEXT = .FALSE.    ! Sep 2023
      WRTABLEFILE_ERRCALC_TEXT = .FALSE. ! Oct 30 2019

      SNTABLE_APPEND_VARNAME = ''
      SNTABLE_APPEND_VALUE   = -9.0

c ----------------------------------------
c check command line arg for namelist file;

       CALL GETARG(1, nmlfile )
       if ( nmlFile(1:6) .EQ. 'NOFILE' ) GOTO 400  ! Jan 5 2016


c ------------------------
c read the nml

300   CONTINUE

      LL = INDEX(nmlfile,' ' ) - 1
      print*,'   Read namelist file: ', nmlfile(1:LL)

      OPEN (
     &    UNIT   = LUNNML
     &   ,file   = nmlfile
     &   ,status = 'OLD'
     &   ,ERR    = 900
     &       )

      READ(LUNNML, NML=SNLCINP, ERR=901, END=902 )

      CLOSE ( UNIT = LUNNML )

400   CONTINUE

c check for namelist over-rides from command line.
      CALL SNLCINP_OVERRIDE()  ! refact with MATCH_NMLKEY (Enable 8.19.2020)

      USE_KCOR_LEGACY = .NOT. USE_KCOR_REFACTOR

c check for cut on simulated search eff;
c if set, then require SEARCHEFF_MASK = 3 =>
c bits 1 & 2 are set.

      IF ( LSIM_SEARCH_SPEC ) THEN
        cutwin_searcheff_mask(1) = 2.9
        cutwin_searcheff_mask(2) = 3.1
      ENDIF

      IF ( LSIM_SEARCH_ZHOST ) THEN  ! Jun 19 2018
        cutwin_searcheff_mask(1) = 4.9
        cutwin_searcheff_mask(2) = 5.1
      ENDIF

c Mar 31 2021: check PHOTFLAG_BITLIST (LSB=0) and compute PHOTFLAG_MSKREJ
      IF ( PHOTFLAG_BITLIST_REJECT(1) .GE. 0 ) THEN
         PHOTFLAG_MSKREJ(1) = 0
         i = 1
         DO WHILE ( PHOTFLAG_BITLIST_REJECT(i) .GE. 0 )
            bit = PHOTFLAG_BITLIST_REJECT(i)
            PHOTFLAG_MSKREJ(1) = IBSET(PHOTFLAG_MSKREJ(1),BIT)
            i = i + 1
         END DO
      ENDIF



      IF ( .not. REDUCE_STDOUT_BATCH ) THEN
        WRITE ( 6 , NML = SNLCINP )
        CALL FLUSH(6)
      ENDIF

      IF ( NFIT_ITERATION .LE. 0 ) THEN
         write(c1err,821) NFIT_ITERATION
821      format('NFIT_ITERATION = ', I3 )
         C2ERR = 'NFIT_ITERATION must be > 0 (see &SNLCINP namelist).'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

c -----------------------------------------
c Compute useful variables from namelist

      NIDFIELD_LIST = PARSE_NML_STRINGLIST(SNFIELD_LIST,60)
      DOALL_SNFIELD = ( SNFIELD_LIST(1) .EQ. 'ALL' )

      i = 1 ; NSNTYPE_LIST=0
      DO WHILE ( SNTYPE_LIST(i) .GE. MNTYPE )
          NSNTYPE_LIST = NSNTYPE_LIST + 1
          i = i + 1
      END DO
      if ( NSNTYPE_LIST .GT. MXLISTNML ) then
          write(c1err,678) 'SNTYPE_LIST', NSNTYPE_LIST, MXLISTNML
678       format(A,2x,I3,' elements exceeds bound.')
          CALL  MADABORT(FNAM, C1ERR, ' ')
      endif

      i = 1 ; NCCDNUM_LIST=0
      DO WHILE ( CCDNUM_LIST(i) > 0 )
          NCCDNUM_LIST = NCCDNUM_LIST + 1
          i = i + 1
      END DO

      i = 1 ; NSIM_TEMPLATE_INDEX_LIST=0
      DO WHILE ( SIM_TEMPLATE_INDEX_LIST(i) > 0 )
          NSIM_TEMPLATE_INDEX_LIST = NSIM_TEMPLATE_INDEX_LIST+1
          i = i + 1
      END DO

      i = 1 ; NSNTYPE_IGNORE=0
      DO WHILE ( SNTYPE_IGNORE(i) .GE. 0 )
          NSNTYPE_IGNORE = NSNTYPE_IGNORE + 1
          i = i + 1
      END DO
      if ( NSNTYPE_IGNORE .GT. MXLISTNML ) then
          write(c1err,678) 'SNTYPE_IGNORE',NSNTYPE_IGNORE,MXLISTNML
          CALL  MADABORT(FNAM, C1ERR, ' ')
      endif

c ------------------------
c count number of photometry versions

      CALL PREP_VERSION_PHOTOMETRY()

c Feb 27 2018: check ZP cut
      NZPCUT = 0
      if ( CUTWIN_ZPADU(1) > 0. ) then
         CUTWIN_ZP(1) = CUTWIN_ZPADU(1)
         CUTWIN_ZP(2) = CUTWIN_ZPADU(2)
         NZPCUT = NZPCUT+1
      endif
      if ( CUTWIN_ZPNPE(1) > 0. ) then
         CUTWIN_ZP(1) = CUTWIN_ZPNPE(1)
         CUTWIN_ZP(2) = CUTWIN_ZPNPE(2)
         NZPCUT = NZPCUT+1
      endif
      IF ( NZPCUT > 1 ) THEN
         C1ERR = 'Cannot specify both CUTWIN_ZPADU and CUTWIN_ZPNPE'
         C2ERR = 'Pick one of these CUTWIN_ZP options.'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

c -----------------------------

      DO_FIT = NFIT_ITERATION .GT. 0

c init some INIXXX parameter for fit
      IF ( DO_FIT ) THEN
         do ipar = 1, MXFITPAR
            INIBND(1,ipar) =  -1.0E4  ! avoid crazy MINUIT excursions
            INIBND(2,ipar) =  +1.0E4
            INIVAL(ipar)   =  -9.0
            INISTP(ipar)   =   0.0
         enddo
      ENDIF

      IF ( MWEBV_SCALE .NE. 1.0 .or. MWEBV_SHIFT .NE. 0.0 ) THEN
         GLOBAL_BANNER = ''
         write(GLOBAL_BANNER,541) MWEBV_SCALE, MWEBV_SHIFT
541      format('Galactic MWEBV -> MWEBV *', F6.3,'  +  ', F6.3 )
        CALL PRBANNER ( GLOBAL_BANNER )
      ENDIF

      IF ( MWEBV_FORCE > -0.01 ) THEN
         GLOBAL_BANNER = ''
         write(GLOBAL_BANNER,542) MWEBV_FORCE
542      format('Force Galactic MWEBV -> ', F6.3 )
        CALL PRBANNER ( GLOBAL_BANNER )
      ENDIF

      IF ( CUTWIN_PHOTPROB(1) > -0.001 .and.
     &     PHOTFLAG_DETECT==0) THEN
         C1ERR = 'Cannot define CUTWIN_PHOTPROB without also'
         C2ERR = 'defining PHOTFLAG_DETECT'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

c ---------------------------
      IF ( VALIDFILENAME(VERSION_REFORMAT_FITS) ) THEN
        OPT_REFORMAT_FITS = IBSET(OPT_REFORMAT_FITS,0) ! set 1st bit
      ENDIF
      IF ( VALIDFILENAME(VERSION_REFORMAT_TEXT) ) THEN    ! Feb 2021
        OPT_REFORMAT_TEXT = IBSET(OPT_REFORMAT_TEXT,0) ! set 1st bit
      ENDIF

c - - - - -
      IF ( SIMLIB_OUT .NE. '' ) SIMLIB_OUTFILE = SIMLIB_OUT

c ---------------------------
c if ENV is in path, make substitution
      CALL ENVreplace(PRIVATE_DATA_PATH)

c check 'pwd' option, which is meant to run split_and_fit on
c different clusters using private data in your `pwd' .
c If interactive, replace invalid pwd/ with a valid './' path.

      IF ( PRIVATE_DATA_PATH .EQ. 'pwd' ) THEN
         PRIVATE_DATA_PATH = '.'
      ENDIF

c if PRIVATE_DATA_PATH points to public $SNDATA_ROOT/lcmerge,
c disalbe PRIVATE_DATA_PATH.
      LL = INDEX(SNDATA_ROOT,' ' ) - 1
      IF ( PRIVATE_DATA_PATH.EQ.SNDATA_ROOT(1:LL)//'/lcmerge')THEN
          PRIVATE_DATA_PATH = ' '
      ENDIF


c Nov 15 2019: abort on obsolete key
      IF ( CUTWIN_NBAND_THRESH(1) > -1.0 .or.
     &     CUTWIN_NBAND_THRESH(2) > -1.0 ) then

         C1ERR = 'Remove obsolete CUTWIN_NBAND_THRESH from &SNLCINP.'
         C2ERR = 'Sorry for the inconvenience.'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

C #################################################

               RETURN

C #################################################

900   c1err = 'Could not open namelist file: '
      c2err = nmlfile(1:80)
      CALL  MADABORT(FNAM, C1ERR, C2ERR)
      GOTO 990

901   C1ERR = 'could not read &SNLCINP namelist'
      c2err = "Check input-namelist file."
      CALL  MADABORT(FNAM, C1ERR, C2ERR )
      GOTO 990

902   C1ERR = 'could not find &SNLCINP namelist'
      c2err = "Check input-namelist file."
      CALL  MADABORT(FNAM, C1ERR, C2ERR )
      GOTO 990

990   IERR = -1
      RETURN
      END  ! end of RDSNNML

C =======================================
CDECK  ID>,  PREP_VERSION_PHOT. 
      SUBROUTINE PREP_VERSION_PHOTOMETRY()

c Created Mar 2022 by R.Kessler
c Check wildcard option to get photometry folders using glob.
c Abort if too many versions.
c
c Aug 2022: set abort trap on VERSION string length

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER i, index_C, LENV, LENF, JSLASH,  NVERS, langFlag
      CHARACTER
     &   FNAM*24
     &  ,cSTRING*(MXCHAR_FILENAME), cFILE*(MXCHAR_FILENAME)
     &  ,VERSION*(2*MXCHAR_VERSION)
      LOGICAL  IGNOREFILE_fortran, IGNORE
      INTEGER  STORE_GLOB_FILE_LIST
      EXTERNAL STORE_GLOB_FILE_LIST
      EXTERNAL GET_GLOB_FILE, RESET_GLOB_FILE_LIST

c ---------- BEGIN -------------

      FNAM = 'PREP_VERSION_PHOTOMETRY'

c check for wild card; e.g.,

      CALL ENVreplace(VERSION_PHOTOMETRY_WILDCARD)
      LENV    = INDEX(VERSION_PHOTOMETRY_WILDCARD,' ') - 1

      IGNORE  = IGNOREFILE_fortran(VERSION_PHOTOMETRY_WILDCARD)

      IF ( .NOT. IGNORE ) THEN
         print*,' '
         print*,' Use glob to find data folders for'
         print*,'     ', VERSION_PHOTOMETRY_WILDCARD(1:LENV)
         call flush(6)

         NVERS = STORE_GLOB_FILE_LIST(cSTRING,LENV)
         langFlag = 1 ! fortran
         DO i = 1, NVERS
            index_C = i - 1  ! C index
            CALL GET_GLOB_FILE(langFlag, index_C, cFILE, LENF)

c  strip off base name after last slash
            JSLASH = INDEX(cFILE,'/', BACK=.TRUE.)
            LENF   = INDEX(cFILE,' ') - 1
            VERSION_PHOTOMETRY(i) = cFILE(JSLASH+1:LENF)

            LENV = INDEX(VERSION_PHOTOMETRY(i),' ') - 1
            print*,' Found ', VERSION_PHOTOMETRY(i)(1:LENV)
         ENDDO
         call flush(6)
         CALL RESET_GLOB_FILE_LIST()
c           STOP ! xxx
      ENDIF

c - - - - -
c Count number of versions, and check string length

      i = 1
      DO WHILE ( VERSION_PHOTOMETRY(i) .NE. 'NULL' )
        N_VERSION = i
        VERSION = VERSION_PHOTOMETRY(i)
        LENV = INDEX(VERSION,' ') - 1
        IF ( LENV .LE. 0 .or. LENV .GE. MXCHAR_VERSION ) THEN
          CALL PRINT_PREABORT_BANNER(FNAM//char(0),40)
          print*,' VERSION = ', VERSION
          print*,' LEN(VERSION) = ', LENV
          print*,' Beware that MXCHAR_VERSION = ', MXCHAR_VERSION
          C1ERR = 'Invalid string len for VERSION'
          write(c2err,17) MXCHAR_VERSION
17        format('VERSION is either blank, or exceeds ',I3,' chars')
          CALL MADABORT(FNAM, C1err, C2err)
        ENDIF


        if ( N_VERSION .GT. MXVERS ) then
          write(C1ERR,61) N_VERSION, MXVERS
61        format('N_VERSION=',I3,' exceeds MXVERS=',I3)
          C2ERR = 'Reduce number of data versions or increase MXVERS'
          CALL  MADABORT(FNAM, C1ERR, C2ERR )
        endif
        i = i + 1
      END DO

      RETURN
      END   ! end PREP_VERSION_PHOTOMETRY

C ======================================
CDECK  ID>,  CHKBOUND. 
      SUBROUTINE CHKARRBOUND(i,MIN,MAX, VARNAME, COMMENT, FUNNAME)

c Nov 2013
c One-line array bound check.
c Abort if index i is outside range MIN to MAX.
c Char input args are used for abort message.

      IMPLICIT NONE

      INTEGER i, MIN, MAX  ! (I) index, MIN,MAX of array
      CHARACTER
     &   VARNAME*(*)  ! (I) name of variable
     &  ,COMMENT*(*)  ! (I) comment string
     &  ,FUNNAME*(*)  ! (I) name of calling function

c local var

      CHARACTER MSG1*80, MSG2*80

C ------------------- BEGIN ------------------

      IF ( i .GE. MIN .and. i .LE. MAX ) RETURN

      write(MSG1,61) VARNAME, i, MIN, MAX, FUNNAME
 61   format(A,'-index ',I4,' outside valid range ',I2,'-',I5, 3x,
     &          '(FUN=',A,')'  )

      MSG2 = COMMENT

      CALL  MADABORT("CHKARRBOUND", MSG1, MSG2)

      RETURN
      END

C ===================================
CDECK  ID>,  CHKCCID. 
      SUBROUTINE NMLCHECK_SNCCID(NMLVARNAME, CCID)

C Apr 26 2013
C Abort if CCID string contains a comma or blank space between
C strings.
C For example, abort on strings such as
C  '04D46,05D446' ,  '04D46 05D446'
C
C NMLVARNAME is the name of the namelist variable,
C for error message only.
C
C ---------------- BEGIN --------------

      IMPLICIT NONE

      CHARACTER NMLVARNAME*(*)  ! (I) name of namelist variable
      CHARACTER CCID*(*)        ! (I) SN CID name

c local variables


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



      INTEGER   JCOMMA, NWD, LEN, MSKOPT
      CHARACTER MSG1*72, MSG2*72, FNAM*30

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------- BEGIN -----------------

      FNAM = 'NMLCHECK_SNCCID'
      JCOMMA   = INDEX(CCID,',')

      LEN      = INDEX(CCID,' ' ) - 1
      MSKOPT   = MSKOPT_PARSE_WORDS_STRING
      NWD      = STORE_PARSE_WORDS(MSKOPT,CCID(1:LEN)//char(0),
     &               FNAM//char(0), LEN, 30)

      IF ( JCOMMA > 0 .or. NWD > 1 ) THEN
         MSG1 = 'Invalid nml variable '
     &           // NMLVARNAME // ' = ' // CCID
         MSG2 = 'No blanks or commas allowed.'
         CALL  MADABORT("NMLCHECK_SNCCID", MSG1, MSG2)
      ENDIF

      RETURN
      END


C ========================================
CDECK  ID>,  INIT_OUTFILES. 
      SUBROUTINE  INIT_OUTFILES(NFIT_PER_SN)


c Created Feb 2012
c
c Call appropriate init function for hbook, root, etc ...
c Note that multiple output files can be initialized
c corresponding to different formats.
c If no files are opened, print warning message but do not abort.
c
c Note that NFIT_PER_SN is the max number of expected fits per SN.
c
c Apr 26 2014: replace HFILE_OPEN and ROOTFILE_OPEN with generic
c              wrapper TABLEFILE_OPEN.
c
c May  3, 2014: call SNLCPAK_INIT only if NFIT_PER_SN > 0
c May 12, 2014: overhaul the ascii format; see TEXTFILE_PREFIX.
c               rename SNFILE_OUT_INIT -> INIT_OUTFILES
c
c Sep 07, 2014: pass TEXTFORMAT to SNLCPAK_INIT()
c
c Dec 10 2017: if NFILT_REMAP_TABLE>0, pass REMAP list of filters
c              to SNLCPAK_INIT
c
c Dec 19 2019: pass SIMFLAG to SNLCPAK_INIT.
c
c Apr 03 2020: add call to  ENVreplace(TEXTFILE_PREFIX)
c
c May 02 2020: begin MARZFILE_OUT (to store WFIRST host spectra for MARZ)
c
c Mar 19 2021: use IGNOREFILE to check usage; e.g., allows
c                ROOTFILE_OUT NONE
c
c Sep 21 2023: fix mistaken 1:40 truncation of VER_PHOT_forC
c
c ------------------------------------------------------

      IMPLICIT NONE

      INTEGER NFIT_PER_SN ! (I) max number of fits to plot per SN


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LENFILE,  IFILETYPE, SIMFLAG

      CHARACTER
     &   FNAM*16
     &  ,COPT*20
     &  ,CFILE*(MXCHAR_FILENAME)
     &  ,TEXTFMT*20

      INTEGER LENV1, LENV2, LENSRVY, LENFILT, LENFMT, LENC
      CHARACTER
     &   SURVEY_forC*(MXCHAR_SURVEY)
     &  ,VER_PHOT_forC*(MXCHAR_VERSION)
     &  ,VER_SNANA_forC*40
     &  ,FILTERS_forC*(MXFILT_OBS)
     &  ,TEXTFMT_forC*20
     &  ,COMMENT_forC*(MXCHAR_VERSION)

c function
      INTEGER  IGNOREFILE, TABLEFILE_OPEN
      EXTERNAL IGNOREFILE, TABLEFILE_OPEN

C --------------- BEGIN -------------

      FNAM = 'INIT_OUTFILES'

      CALL TABLEFILE_INIT();  ! 4/26/2014

c -----------------------------------------
c set strings needed for the SNLCPAK_INIT functio

      LENSRVY      = INDEX(SURVEY_NAME,' ') - 1
      SURVEY_forC  = SURVEY_NAME(1:LENSRVY) // char(0)

      LENV1         = INDEX(VERSION_PHOTOMETRY(1),' ') - 1
      VER_PHOT_forC = VERSION_PHOTOMETRY(1)(1:LENV1) // char(0)

      LENV2         = INDEX(SNANA_VERSION,' ') - 1
      VER_SNANA_forC = SNANA_VERSION(1:LENV2) // char(0)

      LENFILT      = INDEX(SURVEY_FILTERS,' ') - 1
      FILTERS_forC = SURVEY_FILTERS(1:LENFILT) // char(0)
      if ( NFILT_REMAP_TABLE > 0 ) then  ! Dec 2017
         LENFILT      = INDEX(FILTLIST_REMAP_TABLE,' ') - 1
         FILTERS_forC = FILTLIST_REMAP_TABLE(1:LENFILT) // char(0)
      endif

      TEXTFMT      = TEXTFORMAT_TABLE(ITABLE_SNLCPAK)
      LENFMT       = INDEX(TEXTFMT,' ') - 1
      TEXTFMT_forC = TEXTFMT(1:LENFMT) // char(0)

      IF ( OPT_TABLE(ITABLE_SNLCPAK) > 0 ) THEN
         SIMFLAG = 0
         IF ( ISJOB_SIM ) SIMFLAG=1
         CALL SNLCPAK_INIT(SURVEY_forC, VER_PHOT_forC, VER_SNANA_forC,
     &        FILTERS_forC, SIMFLAG, NFIT_PER_SN, TEXTFMT_forC,
     &        LENSRVY, LENV1, LENV2, LENFILT, LENFMT )
      ENDIF

      IF ( OPT_TABLE(ITABLE_SPECPAK) > 0 ) THEN
         TEXTFMT      = TEXTFORMAT_TABLE(ITABLE_SPECPAK)
         LENFMT       = INDEX(TEXTFMT,' ') - 1
         TEXTFMT_forC = TEXTFMT(1:LENFMT) // char(0)
         CALL SPECPAK_INIT(SURVEY_forC, VER_PHOT_forC, TEXTFMT_forC,
     &          LENSRVY, LENV1, LENFMT )
      ENDIF

c -------------------------------------------

      USE_TABLEFILE        = .FALSE.
      USE_TABLEFILE_HBOOK  = .FALSE.
      USE_TABLEFILE_ROOT   = .FALSE.
      USE_TABLEFILE_TEXT   = .FALSE.     ! May 2 2020 (forgot init earlier)
      USE_TABLEFILE_MARZ   = .FALSE.     ! May 2 2020 (new table)

c MARZ (host spectra only)

      LENFILE   = INDEX(MARZFILE_OUT,' ') - 1
      CFILE     = MARZFILE_OUT(1:LENFILE) // char(0)
      IF ( IGNOREFILE(cFILE,LENFILE) == 0 ) THEN
         COPT          = "new" // char(0)
         CALL ENVreplace(MARZFILE_OUT)
         IFILETYPE = TABLEFILE_OPEN(CFILE, COPT, LENFILE, 20)

         USE_TABLEFILE_MARZ = .TRUE.
         USE_TABLEFILE      = .TRUE.

         IF ( IFILETYPE < 0 ) THEN
            C1ERR = 'Could not open MARZ fits-file'
            C2ERR = MARZFILE_OUT(1:LENFILE)
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         ENDIF
      ENDIF


      LENFILE   = INDEX(HFILE_OUT,' ') - 1
      CFILE     = HFILE_OUT(1:LENFILE) // char(0)
      IF ( IGNOREFILE(cFILE,LENFILE) == 0 ) THEN
         COPT          = "new hbook" // char(0)
         USE_TABLEFILE_HBOOK = .TRUE.
         USE_TABLEFILE       = .TRUE.
         IFILETYPE = TABLEFILE_OPEN(CFILE, COPT, LENFILE, 20)

         IF ( IFILETYPE < 0 ) THEN
            C1ERR = 'Could not open HBOOK table-file'
            C2ERR = HFILE_OUT(1:LENFILE)
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         ENDIF
      ENDIF


      LENFILE   = INDEX(ROOTFILE_OUT,' ') - 1
      CFILE     = ROOTFILE_OUT(1:LENFILE) // char(0)
      IF ( IGNOREFILE(cFILE,LENFILE) == 0 ) THEN
         COPT          = "new root" // char(0)
         USE_TABLEFILE_ROOT = .TRUE.
         USE_TABLEFILE      = .TRUE.
         IFILETYPE = TABLEFILE_OPEN(CFILE, COPT, LENFILE, 20)

         IF ( IFILETYPE < 0 ) THEN
            C1ERR = 'Could not open ROOT table-file'
            C2ERR = ROOTFILE_OUT(1:LENFILE)
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         ENDIF
      ENDIF


      LENFILE   = INDEX(TEXTFILE_PREFIX,' ') - 1
      CFILE     = TEXTFILE_PREFIX(1:LENFILE) // char(0)
      IF ( IGNOREFILE(cFILE,LENFILE) == 0 ) THEN
         CALL ENVreplace(TEXTFILE_PREFIX)
         COPT          = "new text" // char(0)
         USE_TABLEFILE_TEXT = .TRUE.
         USE_TABLEFILE      = .TRUE.
         IFILETYPE = TABLEFILE_OPEN(CFILE, COPT, LENFILE, 20)

         IF ( IFILETYPE < 0 ) THEN
            C1ERR = 'Could not open TEXT table-files with PREFIX='
            C2ERR = TEXTFILE_PREFIX(1:LENFILE)
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         ENDIF
      ENDIF

c ----------------------------------------
c Oct 23, 2014: store global comments

      LENC = MXCHAR_VERSION

      COMMENT_forC = 'VERSION_PHOTOMETRY:  '//VER_PHOT_forC(1:LENC)
      CALL STORE_TABLEFILE_COMMENT(COMMENT_forC, LENC)

c ----------------------------------------
c     print warning message if there is no table file
      IF ( .not. USE_TABLEFILE ) THEN
         print*,' '
         write(6,60)
         write(6,61)
     &     'no table-file specified for tables and light curves'
         write(6,60)
         print*,' '
 60      format(T3, 'WARNING: ', 30('<>') )
 61      format(T3, 'WARNING: ', A)
      ENDIF

      RETURN
      END   ! end of INIT_OUTFILES


C ================================================
CDECK  ID>,  INIT_SNTABLE_OPT. 
      SUBROUTINE INIT_SNTABLE_OPTIONS()
c
c Created May 2014 by R.Kessler
c
c Analyze user input string SNTABLE_LIST (&SNLCINP) and set the
c following arrays vs. sparse ITABLE index:
c
c   OPT_TABLE         ! 0,1 --> on,off;  >1 --> other option
c   TEXTFORMAT_TABLE  ! key, csv, col, none
c
c This input string controls which tables are produced
c (SNANA, FITRES, SNLCPAK) and what text formats if
c TEXTFILE_PREFIX is given.
c
c
c Apr 26 2017: check pre-scale option: e.g.  'SNANA(ps:100)'
c Mar 19 2018: check nozphot option
c Jan 29 2019: serach for last non-null char in SNTABLE_LIST to get LENTB
c Jan 30 2019: MXTYPE -> 1000 (was 400)
c May 09 2019:
c  + ITABLE_SPECTRA renamed to ITABLE_MODELSPEC (for SALT2 only)
c       (to avoid confusion with ITABLE_SPECPAK
c  + fix bug parsing options with comma; see new MSKOPT argument
c    to store_PARSE_WORDS()
c
c May 23 2019: add text:host    option ; see WRTABLEFILE_HOST_TEXT
c Oct 30 2019: add text:errcalc option ; see WRTABLEFILE_ERRCALC_TEXT
c Jul 13 2020: no default SNTABLEs if writing rejected epochs
c Mar 17 2021: begin OUTLIER table
c Apr 25 2021: OUTLIER table is automatically disabled for large BIASCOR sim
c Apr 19 2022: disable LCPLOT table for sims in batch mode
c                (to avoid excessive output)
c
c -------------------
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


      INTEGER
     &   itab, iwd, LENS, LENTB, LENOPT, LEN1,LEN2, NOPT, iopt,
     &   PS, NWD, i, MSKOPT, j_colon

      CHARACTER USERSTRING*60, locase_STRING*60, TBNAME*60
      CHARACTER COPT_LIST(10)*20, COPT*40, FNAM*22, C_ARG*100
      CHARACTER cTMPOPT*60
      LOGICAL   MATCH, USEOPT, DO_SNTABLE, DISABLE

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

c ---------------- BEGIN ----------------

      FNAM = 'INIT_SNTABLE_OPTIONS'

c if reformating option is set, turn off all table output
      IF ( OPT_REFORMAT_SALT2 > 0 ) SNTABLE_LIST = ' '
      IF ( OPT_REFORMAT_FITS  > 0 ) SNTABLE_LIST = ' '
      IF ( OPT_REFORMAT_TEXT  > 0 ) SNTABLE_LIST = ' '

c init options to nothing created.

      DO itab = 1, MXTABLE
         OPT_TABLE(itab)          = 0
         PRESCALE_TABLE(itab)     = 1.0
      ENDDO

c Set default text format to output text-table for FITRES only:
c with default SNTABLE_LIST = 'SNANA  FITRES  LCPLOT' ,
c setting TEXTFILE_PREFIX  results in an ascii table for the
c FITRES table only ... just as before. To get ascii table for
c SNANA or LC, user must explicitly request it in the &SNLCINP
c namelist, SNTABLE_LIST = 'SNANA(text:[format])' and SNANA->LCPLOT.

      TEXTFORMAT_TABLE(ITABLE_SNANA)     = 'none'
      TEXTFORMAT_TABLE(ITABLE_FITRES)    = 'key'
      TEXTFORMAT_TABLE(ITABLE_OUTLIER)   = 'key'
      TEXTFORMAT_TABLE(ITABLE_SNLCPAK)   = 'none'
      TEXTFORMAT_TABLE(ITABLE_SPECPAK)   = 'none' ! Apr 2019
      TEXTFORMAT_TABLE(ITABLE_MODELSPEC) = 'none'
      TEXTFORMAT_TABLE(ITABLE_MARZ)      = 'none'



      CUTMASK_SNANA_TABLE = 63  ! default is to add everything in snana table

c -------------------------
      CALL PRBANNER(FNAM)
c ----------------------------------------------
c If using default, replace 'DEFAULT' with actual default value.

      IF ( SNTABLE_LIST .EQ. 'DEFAULT' ) THEN
         SNTABLE_LIST = SNTABLE_LIST_DEFAULT

c  No default SNTABLEs if writing rejected epochs
         IF ( OUT_EPOCH_IGNORE_FILE .NE. ''  ) SNTABLE_LIST = ' '

c  No default SNTABLEs if there is no NML file (Feb 2021)
         IF ( nmlFile(1:6) .EQ. 'NOFILE' ) SNTABLE_LIST = ' '
      ENDIF

c by default the SNID is written out as is
      WRTABLEFILE_IAUC = .FALSE.

c by default, SIM_XXX (truth) values are included for simulation
      WRTABLEFILE_SIMVAR = .TRUE.

c by default, ZPHOT[ERR] and ZPHOT-covariances are included
      WRTABLEFILE_ZPHOT  = .TRUE.

c for TEXT format, exclude HOSTGAL info by default
      WRTABLEFILE_HOST_TEXT  = .FALSE.
      WRTABLEFILE_HOST2_TEXT = .FALSE.

c --------------------------------------
c bail of there is nothing to do.
      DO_SNTABLE = .TRUE.
      IF ( SNTABLE_LIST      .EQ. ' '    ) DO_SNTABLE = .FALSE.
      IF ( SNTABLE_LIST(1:4) .EQ. 'NONE' ) DO_SNTABLE = .FALSE.

      IF ( .NOT. DO_SNTABLE    ) RETURN

c ---------------------------------------
c parse SNTABLE_LIST string

      LENTB = 0
      DO i = 1, MXCHAR_FILENAME
        if ( SNTABLE_LIST(i:i) .NE. ' ' ) LENTB=i  ! last non-null char
      ENDDO
      C_ARG = SNTABLE_LIST(1:LENTB) // char(0)

      MSKOPT = MSKOPT_PARSE_WORDS_STRING+MSKOPT_PARSE_WORDS_IGNORECOMMA
      NWD   = STORE_PARSE_WORDS(MSKOPT, C_ARG,
     &            FNAM//char(0), MXCHAR_FILENAME, 30)

      DO 100 iwd = 1, NWD

         CALL get_PARSE_WORD_fortran(iwd, USERSTRING, LENS);

c convert everything to lower case for parsing so that
c the input is case-insensitive
         CALL loCase(USERSTRING, locase_STRING)

c split string into table name and optional option inside ().
c STRING is of the form "tbName(copt_list)".

         CALL PARSE_SNTABLE_LIST(locase_STRING, TBNAME, NOPT, COPT_LIST)

c check MARZ outpout option (May 2020)
         if ( MARZFILE_OUT .NE. ' ' ) OPT_TABLE(ITABLE_SPECPAK)=2

c - - - - - - - - - - - - - - - - - -
c check table-names

         if ( TBname(1:5) .EQ. 'snana' ) then
            ITAB = ITABLE_SNANA
            OPT_TABLE(ITAB) = 1
            if ( TBname(1:11) .EQ. 'snana+epoch' ) then
               OPT_TABLE(ITAB) = 2     ! include epoch info (Mar 2015)
            endif
            if ( TBname(1:16) .EQ. 'snana+sim_magobs'
     &           .and. LSIM_SNANA) then
               OPT_TABLE(ITAB) = 4     ! include SIM_MAGOBS vs. MJD (1/2019)
            endif

         else if ( TBname(1:6) .EQ. 'fitres' ) then
            ITAB = ITABLE_FITRES
            OPT_TABLE(ITAB) = 1
            if ( TBname(1:15) .EQ. 'fitres+residual' ) then
               OPT_TABLE(ITAB) = 2     ! include epoch fit resids
            endif

         else if ( TBname(1:7) .EQ. 'outlier' ) then
c           OUTLIER table is automatically disabled for large BIASCOR sim
            if ( SIM_BIASCOR_MASK == 0 ) then
              ITAB = ITABLE_OUTLIER
              OPT_TABLE(ITAB) = 1
              NSIGCUT_OUTLIER   = 3.0   ! default outlier def is 3sigma
              FTRUECUT_OUTLIER  = 0.01  ! default requires Ftrue > 0
              SBMAGCUT_OUTLIER  = 999.  ! default is no SBMAG cut (Aug 2021)
            endif
         else if ( TBname(1:6) .EQ. 'lcplot' ) then
            ITAB = ITABLE_SNLCPAK
            DISABLE = ( ISJOB_BATCH .and. ISJOB_SIM )
            IF ( DISABLE ) THEN
               NOPT = 0
               print*,
     &           '  WARNING: disable LCPLOT table for sim-data in batch'
               call flush(6)
            ELSE
               OPT_TABLE(ITAB) = 1
            ENDIF
         else if ( TBname(1:8) .EQ. 'specplot' ) then
            ITAB = ITABLE_SPECPAK  ! spectra in the data files
            OPT_TABLE(ITAB) = 1

         else if ( TBname(1:9) .EQ. 'modelspec' ) then
            ITAB = ITABLE_MODELSPEC  ! SALT2 model spec
            OPT_TABLE(ITAB) = 1
         else if ( TBname(1:7) .EQ. 'spectra' ) then
            ITAB = ITABLE_MODELSPEC  ! legacy key for SALT2 model spec
            OPT_TABLE(ITAB) = 1

         else if ( TBname(1:8) .EQ. 'nosimvar' ) then ! option, not a table
            WRTABLEFILE_SIMVAR = .FALSE.  ! July 2016

         else if ( TBname(1:7) .EQ. 'nozphot' ) then ! option, not a table
            WRTABLEFILE_ZPHOT = .FALSE.  ! Mar 2018

         else
            C1ERR = 'Unrecognized table name : ' // TBname(1:20)
            C2ERR = 'Check manual'
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         endif

c check for options inside ()
         DO 200 iopt = 1, NOPT
            COPT     = COPT_LIST(iopt)
            LENOPT   = index(COPT,' ') - 1
            USEOPT   = .FALSE.
            j_colon  = INDEX(copt,':')

            MATCH= ( copt(1:5) .EQ. 'text:' )
            if ( MATCH ) then
               cTMPOPT = copt(6:LENOPT) // ' '
               if( cTMPOPT(1:5) .EQ. 'host2' ) then
                  WRTABLEFILE_HOST2_TEXT = .TRUE.  ! for SNANA table
               else if( cTMPOPT(1:4) .EQ. 'host' ) then
                  WRTABLEFILE_HOST_TEXT = .TRUE.  ! for SNANA table
               else if ( cTMPOPT(1:7) .EQ. 'errcalc' ) then
                  WRTABLEFILE_ERRCALC_TEXT = .TRUE.  ! for LCPLOT table
               else
                  TEXTFORMAT_TABLE(itab) = cTMPOPT(1:8) ! format
               endif
               USEOPT = .TRUE.
            endif

            MATCH = (copt(1:5) .EQ. 'mxlc:' )
            if ( MATCH  .and. ITAB .EQ. ITABLE_SNLCPAK) then
               read(copt(6:LENOPT),*) MXLC_PLOT
               USEOPT = .TRUE.
            endif

            MATCH = ( copt(1:8) .EQ. 'cutmask:' )
            if ( MATCH  .and. ITAB .EQ. ITABLE_SNANA ) then
               read(copt(9:LENOPT),*) CUTMASK_SNANA_TABLE
               USEOPT = .TRUE.
            endif

            MATCH = ( copt(1:4) .EQ. 'iauc' )
            if ( MATCH ) then
               WRTABLEFILE_IAUC = .TRUE.
               USEOPT           = .TRUE.
            endif

            MATCH = ( copt(1:3) .EQ. 'ps:' )
            if ( MATCH ) then
               read(copt(4:LENOPT),*) PS
               PRESCALE_TABLE(itab) = PS
               USEOPT           = .TRUE.
            endif

            MATCH = copt(1:5) .EQ. 'nsig:'
            IF ( MATCH ) THEN
               read(copt(6:LENOPT),*) NSIGCUT_OUTLIER
               USEOPT = .TRUE.
            ENDIF
            MATCH = copt(1:6) .EQ. 'ftrue:'
            IF ( MATCH ) THEN
               read(copt(7:LENOPT),*) FTRUECUT_OUTLIER
               USEOPT = .TRUE.
            ENDIF
            MATCH = copt(1:6) .EQ. 'sbmag:'
            IF ( MATCH ) THEN
               read(copt(7:LENOPT),*) SBMAGCUT_OUTLIER
               USEOPT = .TRUE.
            ENDIF

            if ( .NOT. USEOPT ) then
               LENTB = index(TBNAME,' ') - 1
               C1ERR = 'Invalid option: ' // COPT(1:LENOPT)
               C2ERR = 'for Table = ' // TBNAME(1:LENTB)
               CALL  MADABORT(FNAM, C1ERR, C2ERR)
            endif

 200     CONTINUE

 100  CONTINUE  ! end loop over table names

c ------------
c if LCPLOT is not specified, set MXLC_PLOT to zero.
      IF  ( OPT_TABLE(ITABLE_SNLCPAK) == 0 .and.
     &      OPT_TABLE(ITABLE_SPECPAK) == 0  )    MXLC_PLOT = 0

c -------------
c summarize

      ITAB = ITABLE_SNANA
      write(6,40) 'SNANA',  OPT_TABLE(ITAB), TEXTFORMAT_TABLE(ITAB)

      ITAB = ITABLE_FITRES
      write(6,40) 'FITRES', OPT_TABLE(ITAB), TEXTFORMAT_TABLE(ITAB)

      ITAB = ITABLE_SNLCPAK
      write(6,41) 'SNLCPAK', MXLC_PLOT, TEXTFORMAT_TABLE(ITAB)
      ITAB = ITABLE_SPECPAK
      write(6,41) 'SPECPAK', MXLC_PLOT, TEXTFORMAT_TABLE(ITAB)

      ITAB = ITABLE_MODELSPEC
      write(6,40) 'MODELSPEC', OPT_TABLE(ITAB),TEXTFORMAT_TABLE(ITAB)

      ITAB = ITABLE_MARZ
      write(6,40) 'MARZ', OPT_TABLE(ITAB),TEXTFORMAT_TABLE(ITAB)

 40   format(T5,A9,'-table: USE=',I1,       3x, 'TEXTFORMAT=',A4 )
 41   format(T5,A9,'-table: MXLC_PLOT=',I6, 3x, 'TEXTFORMAT=',A4 )

      write(6,51) 'SNANA', CUTMASK_SNANA_TABLE
51    format(T5,A9,'-table: select CUTFLAG_SNANA & ', I3 )

      if ( WRTABLEFILE_HOST_TEXT ) then
         print*,'   Include best-match HOSTGAL info in TEXT tables.'
      endif
      if ( WRTABLEFILE_HOST2_TEXT ) then
         print*,'   Include  HOSTGAL & HOSTGAL2 info in TEXT tables.'
      endif

      if ( WRTABLEFILE_IAUC ) then
         print*,'    All tables: write CID=IAUC name instead of SNID '
      endif

      call flush(6)

c --------

c check option to remap filters for table output.
c e..g, multiple V-bands that are similar in different
c subsurveys can be combined into a single V band.
c See manual explanation of SNTABLE_FILTER_REMAP

      IF ( SNTABLE_FILTER_REMAP .EQ. '' ) THEN
        LEN1 = 0
      ELSE
        LEN1 = INDEX(SNTABLE_FILTER_REMAP,'->', BACK=.TRUE.) + 3
      ENDIF

      LEN2 = INDEX(SURVEY_FILTERS,' ') - 1

      CALL  FILTER_REMAP_INIT(
     &     SNTABLE_FILTER_REMAP(1:LEN1)//char(0),   ! (I) user-input string
     &     SURVEY_FILTERS(1:LEN2)//char(0),         ! (I) valid filters
     &     NFILT_REMAP_TABLE,           ! (O) number of remapped bands
     &     IFILTLIST_REMAP_TABLE,       ! (O) index list of remapped bands
     &     FILTLIST_REMAP_TABLE,        ! (O) string list of ...
     &     LEN1, LEN2, MXFILT_ALL )

      FILTLIST_REMAP_TABLE =
     &  FILTLIST_REMAP_TABLE(1:NFILT_REMAP_TABLE) // ' '

c option to compute width variables
      CALL GET_SIM_LCWIDTH(0)

      RETURN
      END     ! end of INIT_SNTABLE_OPTIONS

C =================================
CDECK  ID>,  GET_SIM_LCWIDTH. 
      SUBROUTINE GET_SIM_LCWIDTH(MODE)

c Feb 2019
c For each filter, compute and store SIM_LCWIDTH(ifilt)
c
      IMPLICIT NONE
      INTEGER MODE  ! (I) 0=init, 1=get width


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER MXEP_LCWIDTH
      PARAMETER ( MXEP_LCWIDTH = 200)

      REAL*8  SIM_MAGOBS(MXEP_LCWIDTH), SIM_MJD(MXEP_LCWIDTH)
      REAL*8  WIDTH
      INTEGER
     &  IFILT, IFILT_OBS, EP, EPMIN, EPMAX, NEWMJD, NOBS, ERRFLAG

      CHARACTER FNAM*16
c functions
      REAL*8   get_lightCurveWidth
      EXTERNAL INIT_LIGHTCURVEWIDTH, get_lightCurveWidth

C -------- BEGIN ----------

      FNAM = 'GET_SIM_LCWIDTH'
      IF ( OPTSIM_LCWIDTH == 0 ) RETURN
      IF ( .NOT. LSIM_SNANA    ) RETURN

      IF (MODE == 0 ) THEN
c  init only
         CALL INIT_LIGHTCURVEWIDTH()
         RETURN
      ENDIF

c loop over each filter and strip off MJD and true MAG into
c separate array to pass to get_lightCurveWidth function.

      DO 100 ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         NOBS = 0
         DO 150  NEWMJD = 1, ISNLC_NEWMJD_STORE
            EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
            EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
            DO 151 EP = EPMIN, EPMAX
               if ( ISNLC_IFILT_OBS(ep) .NE. ifilt_obs ) goto 151
               NOBS = NOBS + 1
               SIM_MJD(NOBS)    = SNLC8_MJD(ep)
               SIM_MAGOBS(NOBS) = SIM_EPMAGOBS(ep)
151        CONTINUE
150      CONTINUE

         WIDTH = get_lightCurveWidth(OPTSIM_LCWIDTH,
     &               NOBS,SIM_MJD, SIM_MAGOBS, ERRFLAG, FNAM,16)
         SIM_LCWIDTH(ifilt) = SNGL(WIDTH)

c         print*,' xxx WIDTH: ', ifilt, ifilt_obs, WIDTH
 100  CONTINUE ! end IFILT loop

      RETURN
      END

C =============================================
CDECK  ID>,  PROB_TRUEFLUX_CALC. 
      SUBROUTINE PROB_TRUEFLUX_CALC(ep)

c Created Apr 6 2021
c For fakes or SIM, compute chi2 = \Sum[F-Ftrue]/sigma_F^2 per band.
c Compute PROB(chi2,NDOF) for each band.
c
c  ep = 0  -> init sums to zero
c  ep > 0  -> increment chi2
c  ep = -1 -> compute prob(chi2,Ndof)
c --------------

      INTEGER EP  ! (I)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,TRUECHI2COM. inserted below by ypatchy. 

c for fakes and sim, compute sum[F-Ftrue]^2/sigma^2 per band
c The zeroth element is all bands together.

      REAL
     &   CHI2_TRUEFLUX(0:MXFILT_ALL)
     &  ,PROB_TRUEFLUX(0:MXFILT_ALL)

      INTEGER NDOF_TRUEFLUX(0:MXFILT_ALL)

      COMMON /  TRUECHI2COM /
     &   NDOF_TRUEFLUX, CHI2_TRUEFLUX, PROB_TRUEFLUX


      INTEGER IFILT_OBS, IFILT, NDOF
      REAL CHI2
      REAL*8 CHI8, PROB8

      REAL*8 PROB_CHI2NDOF
      EXTERNAL PROB_CHI2NDOF
C ------------- BEGIN -------------

      IF ( .NOT. LPROB_TRUEFLUX ) RETURN
      IF ( .NOT. ISJOB_SIM      ) RETURN ! fakes or SNANA sim

      IF ( ep == 0 ) THEN
         DO IFILT = 0, NFILTDEF_SURVEY
            NDOF_TRUEFLUX(ifilt) =   -1
            CHI2_TRUEFLUX(ifilt) =  0.0
            PROB_TRUEFLUX(ifilt) = -9.0
         ENDDO
         RETURN
      ENDIF

c - - - - -
      IF ( EP > 0 ) THEN
         IF ( SIM_EPFLUXCAL(ep) > 0.1 ) THEN
         ! increment chi2
            IFILT_OBS = ISNLC_IFILT_OBS(ep)
            IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
            CHI2      = SIM_EPCHI2FLUX(ep)
            CHI2_TRUEFLUX(ifilt) = CHI2_TRUEFLUX(ifilt) + CHI2
            NDOF_TRUEFLUX(ifilt) = NDOF_TRUEFLUX(ifilt) + 1

            CHI2_TRUEFLUX(0) = CHI2_TRUEFLUX(0) + CHI2
            NDOF_TRUEFLUX(0) = NDOF_TRUEFLUX(0) + 1
         ENDIF
      ELSE
         ! compute FITPROB per band
         DO ifilt    = 1, NFILTDEF_SURVEY
            CHI8     = DBLE( CHI2_TRUEFLUX(ifilt) )
            NDOF     = NDOF_TRUEFLUX(ifilt)
            if ( NDOF > 2 ) then
               PROB8    = PROB_CHI2NDOF(CHI8,NDOF)
               PROB_TRUEFLUX(ifilt) = SNGL(PROB8)
            endif

c global with all filters
            CHI8     = DBLE( CHI2_TRUEFLUX(0) )
            NDOF     = NDOF_TRUEFLUX(0)
            if ( NDOF > 2 ) then
               PROB8    = PROB_CHI2NDOF(CHI8,NDOF)
               PROB_TRUEFLUX(0) = SNGL(PROB8)
            endif

        ENDDO
      ENDIF

      RETURN
      END        ! end PROB_TRUEFLUX_CALC


C =============================================
CDECK  ID>,  PARSE_SNTABLE_LIST. 
      SUBROUTINE PARSE_SNTABLE_LIST(USERSTRING, TABLENAME, NOPT, COPT)

c parse USERSTRING from SNTABLE_LIST;
c rdturn name of table and string of options.

      IMPLICIT NONE

      CHARACTER
     &   USERSTRING*(*)  ! (I) user-input string from SNTABLE_LIST
     &  ,TABLENAME*20    ! (O) name of table
     &  ,COPT(10)*20     ! (O) list of options

      INTEGER NOPT       ! (O) numbef of COPT options

      LOGICAL DONEXT

c local args

      INTEGER jp1, jp2, j, i, LENOPT
      CHARACTER COPT_LIST*60, CTMP*60 ! comma-separated list

C ----------------- BEGIN ----------------

c init output args
      TABLENAME = 'UNKNOWN'
      NOPT = 0
      do i = 1, 10
        COPT(i) = ''
      enddo

c ---------------------

      jp1  = index(USERSTRING,'(')
      jp2  = index(USERSTRING,')')
      if ( jp1 > 0 ) then
         TABLENAME  = USERSTRING(1:jp1-1)
         COPT_LIST  = USERSTRING(jp1+1:jp2-1)
      else
         TABLENAME  = USERSTRING
         RETURN
      endif

c if we get here then parse comma-separated list of options
c in COPT_LIST

      LENOPT = index(COPT_LIST,' ' ) - 1
      DONEXT = .TRUE.
      CTMP   = COPT_LIST

      DO 100 WHILE ( DONEXT )
         NOPT  = NOPT + 1
         j     = index(CTMP,',')
         if ( j .LE. 0  ) j = LENOPT + 1
         COPT(NOPT) = CTMP(1:j-1)
         DONEXT     = j < LENOPT
         CTMP       = CTMP(j+1:LENOPT)

         if ( NOPT > 10 ) then
            CALL  MADABORT("PARSE_SNTABLE_LIST",
     &               'NOPT > 10 ???          ',
     &               'Something is wrong     ' )
         endif
 100  CONTINUE

      RETURN
      END   ! end of PARSE_SNTABLE_LIST


C ================================================
CDECK  ID>,  SNLCINP_OVERRIDE. 
      SUBROUTINE SNLCINP_OVERRIDE()
c
c Created July 2020 by R.Kessler [refactored]
c Check command-line args for user-option to override
c namelist values. Check for two styles of override:
c
c Legacy style is space-sparated such as    CUTWIN_SNRMAX 5 999
c New style has equal sign and no spaces,   CUTWIN_SNRMAX=5,999
c
c Beware that some arguments are comma-sep lists, so need
c to be careful about when to split by comma, and when
c not so split by comma.
c
c Oct 22 2020:
c   + double string length for LINE_ARGS and ARGLIST to allow for
c     long comma-sep strings.
c
c Nov 23 2020: read OPT_YAML
c
c Dec 08 2020:
c   + fix bug setting USE_LINE_ARGS(iuse) to trap bad args.
c     last few months we were vulnerable to bad args that were
c     ignored instead of causing abort.
c
c ----------

      IMPLICIT  NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c local var

      INTEGER iArg, LL, ilast, iuse, NVERLOC
      CHARACTER STRING_LIST*60
      CHARACTER ARG*(MXCHAR_ARG), ARGLIST(MXKEY_ARGS)*(MXCHAR_ARG)
      LOGICAL LSNIGNORE, DO_STOP, FOUND_MATCH_LEGACY, FOUND_MATCH_REFAC
      LOGICAL HAS_EQUAL, VALID_ARGLIST, LDMP

c functions
      LOGICAL MATCH_NMLKEY
      INTEGER PARSE_INTLIST

c ------------- BEGIN -------------

      LDMP = .FALSE.
      iArg = 2 ;   ilast = 2 ;      NVERLOC = 0

      DO 4444 WHILE ( iArg .LE. NLINE_ARGS )

        CALL GETARG(iArg, ARG)
        LL = INDEX (ARG, ' ' ) - 1
        HAS_EQUAL = ( INDEX(ARG,'=') > 0 )

        print*,'     PROCESS COMMAND LINE ARG: ', ARG(1:LL)

        if ( LDMP ) then
          print*,' xxx ===================================== '
          print*,' xxx iArg,ARG = ', iArg, ARG(1:40)
        endif

        CALL FLUSH(6)
        ARGLIST(1) = ''

         if ( MATCH_NMLKEY('VERSION_PHOTOMETRY',1,iArg,ARGLIST) ) then
            CALL PARSE_COMMASEP_LIST('VERSION_PHOTOMETRY',
     &                                 ARGLIST(1))

         else if(MATCH_NMLKEY('VERSION_PHOTOMETRY_WILDCARD',
     &                1, iArg, ARGLIST) ) then
            VERSION_PHOTOMETRY_WILDCARD = ARGLIST(1)(1:MXCHAR_VERSION)
         else if(MATCH_NMLKEY('VERSION_REFORMAT_FITS',
     &                1, iArg, ARGLIST) ) then
            VERSION_REFORMAT_FITS = ARGLIST(1)(1:MXCHAR_VERSION)
         else if(MATCH_NMLKEY('VERSION_REFORMAT_TEXT',
     &                1, iArg, ARGLIST) ) then
            VERSION_REFORMAT_TEXT = ARGLIST(1)(1:MXCHAR_VERSION)

         else if ( MATCH_NMLKEY('OPT_YAML',
     &             1, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) OPT_YAML

         else if ( MATCH_NMLKEY('OPT_REFORMAT_FITS',
     &             1, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) OPT_REFORMAT_FITS

         else if ( MATCH_NMLKEY('OPT_REFORMAT_TEXT',
     &              1, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) OPT_REFORMAT_TEXT

         else if ( MATCH_NMLKEY('OPT_REFORMAT_SPECTRA',
     &             1, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) OPT_REFORMAT_SPECTRA

         else if ( MATCH_NMLKEY('OPT_REFORMAT_SALT2',
     &              1, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) OPT_REFORMAT_SALT2

         else if ( MATCH_NMLKEY('REFORMAT_KEYS',
     &              1, iArg, ARGLIST) ) then
             REFORMAT_KEYS = ARGLIST(1)(1:100)

         else if ( MATCH_NMLKEY('PRIVATE_DATA_PATH',
     &               1, iArg, ARGLIST) ) then
            PRIVATE_DATA_PATH = ARGLIST(1)(1:MXCHAR_PATH)

         else if ( MATCH_NMLKEY('PRIVATE_CUTWIN_STRING',
     &            1, iArg, ARGLIST) ) then
            PRIVATE_CUTWIN_STRING = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('PRIVATE_VARNAME_READLIST',
     &            1, iArg, ARGLIST) ) then
            PRIVATE_VARNAME_READLIST = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('EARLYLC_STRING',
     &             1, iArg, ARGLIST) ) then
           EARLYLC_STRING = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('REQUIRE_EPOCHS_STRING',
     &             1, iArg, ARGLIST) ) then
           REQUIRE_EPOCHS_STRING = ARGLIST(1)(1:100)

         else if ( MATCH_NMLKEY('DUMP_STRING',
     &             1, iArg, ARGLIST) ) then
           DUMP_STRING = ARGLIST(1)(1:100)

         else if ( MATCH_NMLKEY('FILTER_UPDATE_PATH',
     &             1,iArg, ARGLIST) ) then
           FILTER_UPDATE_PATH = ARGLIST(1)(1:MXCHAR_PATH)

         else if ( MATCH_NMLKEY('NONSURVEY_FILTERS',
     &             1, iArg, ARGLIST) ) then
           NONSURVEY_FILTERS = ARGLIST(1)(1:MXFILT_ALL)

         else if ( MATCH_NMLKEY('FILTER_REPLACE',
     &             1, iArg, ARGLIST) ) then
           FILTER_REPLACE = ARGLIST(1)(1:MXFILT_ALL)

         else if ( MATCH_NMLKEY('FILTLIST_LAMSHIFT',
     &             1, iArg, ARGLIST) ) then
           FILTLIST_LAMSHIFT = ARGLIST(1)(1:MXFILT_ALL)

         else if ( MATCH_NMLKEY('USERTAGS_FILE',
     &             1, iArg, ARGLIST) ) then
           USERTAGS_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('VPEC_FILE',
     &             1, iArg, ARGLIST) ) then
           VPEC_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('KCOR_FILE',
     &             1, iArg, ARGLIST) ) then
           KCOR_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)
         else if ( MATCH_NMLKEY('OVERRIDE_RESTLAM_BOUNDARY',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) OVERRIDE_RESTLAM_BOUNDARY

         else if ( MATCH_NMLKEY('HEADER_OVERRIDE_FILE',
     &             1, iArg, ARGLIST) ) then
           HEADER_OVERRIDE_FILE = ARGLIST(1)
         else if ( MATCH_NMLKEY('SIM_HEADER_OVERRIDE_FILE',
     &             1, iArg, ARGLIST) ) then
           SIM_HEADER_OVERRIDE_FILE = ARGLIST(1)

c LSNIGNORE

         else if ( MATCH_NMLKEY('INTERP_OPT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) INTERP_OPT

         else if ( MATCH_NMLKEY('HFILE_OUT',
     &             1, iArg, ARGLIST) ) then
           HFILE_OUT = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('ROOTFILE_OUT',
     &             1, iArg, ARGLIST) ) then
           ROOTFILE_OUT = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('TEXTFILE_PREFIX',
     &             1, iArg, ARGLIST) ) then
           TEXTFILE_PREFIX = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('MARZFILE_OUT',
     &             1, iArg, ARGLIST) ) then
           MARZFILE_OUT = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SNTABLE_LIST',
     &             1, iArg, ARGLIST) ) then
           SNTABLE_LIST = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SNTABLE_FILTER_REMAP',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SNTABLE_FILTER_REMAP

         else if ( MATCH_NMLKEY('SNTABLE_APPEND',
     &             2, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SNTABLE_APPEND_VARNAME
           READ(ARGLIST(2),*) SNTABLE_APPEND_VALUE

         else if ( MATCH_NMLKEY('OPTSIM_LCWIDTH',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) OPTSIM_LCWIDTH

         else if ( MATCH_NMLKEY('SNCID_IGNORE_FILE',
     &             1, iArg, ARGLIST) ) then
           SNCID_IGNORE_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SNMJD_OUT_FILE',
     &             1, iArg, ARGLIST) ) then
           SNMJD_LIST_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SNMJD_OUT_FILE',
     &             1, iArg, ARGLIST) ) then
           SNMJD_LIST_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('EPOCH_IGNORE_FILE',
     &             1, iArg, ARGLIST) ) then
           EPOCH_IGNORE_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('OUT_EPOCH_IGNORE_FILE',
     &             1, iArg, ARGLIST) ) then
           OUT_EPOCH_IGNORE_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('NFIT_ITERATION',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) NFIT_ITERATION

         else if ( MATCH_NMLKEY('USE_MINOS',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USE_MINOS

         else if ( MATCH_NMLKEY('MINUIT_PRINT_LEVEL',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MINUIT_PRINT_LEVEL

         else if ( MATCH_NMLKEY('MXLC_PLOT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MXLC_PLOT

         else if ( MATCH_NMLKEY('MJDPERIOD_PLOT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MJDPERIOD_PLOT

         else if ( MATCH_NMLKEY('MJDSHIFT_PLOT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MJDSHIFT_PLOT

         else if ( MATCH_NMLKEY('DTOBS_MODEL_PLOT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) DTOBS_MODEL_PLOT

         else if ( MATCH_NMLKEY('PHOTFLAG_MSKREJ',
     &             2, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) PHOTFLAG_MSKREJ(1)
           READ(ARGLIST(2),*) PHOTFLAG_MSKREJ(2)

         else if ( MATCH_NMLKEY('PHOTFLAG_BITLIST_REJECT',
     &             1, iArg, ARGLIST) ) then
           if ( ARGLIST(1) .NE. 'NONE' ) then
              CALL PARSE_COMMASEP_LIST('PHOTFLAG_BITLIST',ARGLIST(1))
           endif

         else if ( MATCH_NMLKEY('PHOTFLAG_DETECT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) PHOTFLAG_DETECT

         else if ( MATCH_NMLKEY('PHOTFLAG_TRIGGER',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) PHOTFLAG_TRIGGER
c - - - - - -
         else if ( MATCH_NMLKEY('MULTISEASON_OPTMASK',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MULTISEASON_OPTMASK

         else if ( MATCH_NMLKEY('MULTISEASON_TGAP',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MULTISEASON_TGAP

         else if ( MATCH_NMLKEY('MULTISEASON_NREJECT_OUTLIER',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MULTISEASON_NREJECT_OUTLIER

         else if ( MATCH_NMLKEY('MULTISEASON_CHI2RED_ACTIVE',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MULTISEASON_CHI2RED_ACTIVE

         else if ( MATCH_NMLKEY('CUTWIN_NSEASON_ACTIVE',
     &             2, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) CUTWIN_NSEASON_ACTIVE(1)
           READ(ARGLIST(2),*) CUTWIN_NSEASON_ACTIVE(2)

c - - - - -
         else if ( MATCH_NMLKEY('LSIM_SEARCH_SPEC',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LSIM_SEARCH_SPEC

         else if ( MATCH_NMLKEY('LSIM_SEARCH_ZHOST',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LSIM_SEARCH_ZHOST
         else if ( MATCH_NMLKEY('LSIM_SEARCH_zHOST',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LSIM_SEARCH_ZHOST

         else if ( MATCH_NMLKEY('DEBUG_FLAG',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) DEBUG_FLAG

         else if ( MATCH_NMLKEY('LPROB_TRUEFLUX',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LPROB_TRUEFLUX

         else if ( MATCH_NMLKEY('LDMP_SNFAIL',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LDMP_SNFAIL

         else if ( MATCH_NMLKEY('LDMP_SATURATE',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LDMP_SATURATE

         else if ( MATCH_NMLKEY('USESIM_SNIA',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USESIM_SNIA
         else if ( MATCH_NMLKEY('USESIM_NONIA',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USESIM_NONIA

         else if ( MATCH_NMLKEY('USE_SNHOST_ZPHOT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USE_SNHOST_ZPHOT

         else if ( MATCH_NMLKEY('USE_HOSTGAL_PHOTOZ',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USE_HOSTGAL_PHOTOZ

         else if ( MATCH_NMLKEY('USESIM_TRUEFLUX',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USESIM_TRUEFLUX

         else if ( MATCH_NMLKEY('RESTORE_MWEBV_ERR_BUG',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) RESTORE_MWEBV_ERR_BUG

         else if ( MATCH_NMLKEY('RESTORE_WRONG_VPEC',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) RESTORE_WRONG_VPEC

         else if ( MATCH_NMLKEY('RESTORE_OVERRIDE_ZBUG',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) RESTORE_OVERRIDE_ZBUG

         else if ( MATCH_NMLKEY('REQUIRE_DOCANA',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) REQUIRE_DOCANA

         else if ( MATCH_NMLKEY('USE_KCOR_REFACTOR',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USE_KCOR_REFACTOR

         else if ( MATCH_NMLKEY('USE_MWCOR',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) USE_MWCOR

c - - - -
         else if ( MATCH_NMLKEY('LTEST_U3BAND',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LTEST_U3BAND
         else if ( MATCH_NMLKEY('LTEST_MAG',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LTEST_MAG
         else if ( MATCH_NMLKEY('LTEST_INTERP',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LTEST_INTERP
         else if ( MATCH_NMLKEY('LTEST_KCOR',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) LTEST_KCOR

c - - - -
         else if ( MATCH_NMLKEY('OPT_SETPKMJD',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) OPT_SETPKMJD

         else if ( MATCH_NMLKEY('MJDWIN_SETPKMJD',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MJDWIN_SETPKMJD

         else if ( MATCH_NMLKEY('SNRCUT_SETPKMJD',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SNRCUT_SETPKMJD

         else if ( MATCH_NMLKEY('SHIFT_SETPKMJD',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SHIFT_SETPKMJD

         else if ( MATCH_NMLKEY('SNCCID_LIST',
     &             1, iArg, ARGLIST) ) then
           if ( ARGLIST(1) .NE. 'NONE' ) then
              CALL PARSE_COMMASEP_LIST('SNCCID_LIST', ARGLIST(1))
              CUTWIN_CID(1) = 0;  CUTWIN_CID(2)=0
           endif

         else if ( MATCH_NMLKEY('SNCCID_IGNORE',  ! July 2023
     &             1, iArg, ARGLIST) ) then
           if ( ARGLIST(1) .NE. 'NONE' ) then
              CALL PARSE_COMMASEP_LIST('SNCCID_IGNORE', ARGLIST(1))
           endif

         else if ( MATCH_NMLKEY('SNCID_LIST_FILE',
     &             1, iArg, ARGLIST) ) then
           SNCID_LIST_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)
           CUTWIN_CID(1) = 0;  CUTWIN_CID(2)=0

         else if ( MATCH_NMLKEY('OPT_SNCID_LIST',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) OPT_SNCID_LIST


         else if ( MATCH_NMLKEY('MXEVT_PROCESS',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MXEVT_PROCESS

         else if ( MATCH_NMLKEY('MXEVT_CUTS',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MXEVT_CUTS

         else if ( MATCH_NMLKEY('MXLC_FIT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) MXLC_FIT

         else if ( MATCH_NMLKEY('SIM_TEMPLATE_INDEX_LIST',
     &             1, iArg, ARGLIST) ) then
           STRING_LIST = ARGLIST(1)(1:60)
           NSIM_TEMPLATE_INDEX_LIST =  ! select SIM_TEMPLATE INDICE
     &        PARSE_INTLIST(STRING_LIST,SIM_TEMPLATE_INDEX_LIST)

         else if ( MATCH_NMLKEY('SIMLIB_OUT',
     &             1, iArg, ARGLIST) ) then
           SIMLIB_OUT = ARGLIST(1)(1:MXCHAR_FILENAME)
         else if ( MATCH_NMLKEY('SIMLIB_OUTFILE', ! same as SIMLIB_OUT
     &             1, iArg, ARGLIST) ) then
           SIMLIB_OUTFILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SIMLIB_ZPERR_LIST',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SIMLIB_ZPERR_LIST

         else if ( MATCH_NMLKEY('OPT_SIMLIB_OUT',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) OPT_SIMLIB_OUT

         else if ( MATCH_NMLKEY('SIMLIB_OUT_TMINFIX',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SIMLIB_OUT_TMINFIX

         else if ( MATCH_NMLKEY('NONLINEARITY_FILE',
     &             1, iArg, ARGLIST) ) then
           NONLINEARITY_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SNFIELD_LIST',
     &             1, iArg, ARGLIST) ) then
           SNFIELD_LIST(1) = ARGLIST(1)(1:60)
           SNFIELD_LIST(2) = ''

         else if ( MATCH_NMLKEY('JOBSPLIT',
     &             2, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) JOBSPLIT(1)
           READ(ARGLIST(2),*) JOBSPLIT(2)
           ISJOB_BATCH = .TRUE.
           REDUCE_STDOUT_BATCH = ( JOBSPLIT(1) .GT. 1 )

         else if ( MATCH_NMLKEY('JOBSPLIT_EXTERNAL',
     &             2, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) JOBSPLIT_EXTERNAL(1)
           READ(ARGLIST(2),*) JOBSPLIT_EXTERNAL(2)

         else if ( MATCH_NMLKEY('SIM_PRESCALE',
     &             1, iArg, ARGLIST) ) then
           READ(ARGLIST(1),*) SIM_PRESCALE

        else if ( MATCH_NMLKEY('CUTWIN_CID',
     &            2, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) CUTWIN_CID(1)
             READ(ARGLIST(2),*) CUTWIN_CID(2)

        else if ( MATCH_NMLKEY('CUTWIN_SNTYPE',
     &            2, iArg, ARGLIST) ) then
             READ(ARGLIST(1),*) CUTWIN_SNTYPE(1)
             READ(ARGLIST(2),*) CUTWIN_SNTYPE(2)

c - - - -
         else if ( MATCH_NMLKEY('SNTYPE_LIST',
     &             1, iArg, ARGLIST) ) then
           STRING_LIST = ARGLIST(1)(1:60)
           NSNTYPE_LIST = PARSE_INTLIST(STRING_LIST,SNTYPE_LIST)

         else if ( MATCH_NMLKEY('CCDNUM_LIST',
     &             1, iArg, ARGLIST) ) then
           STRING_LIST = ARGLIST(1)(1:60)
           NCCDNUM_LIST = PARSE_INTLIST(STRING_LIST,CCDNUM_LIST)

         else if ( MATCH_NMLKEY('SNTYPE_IGNORE',
     &             1, iArg, ARGLIST) ) then
           STRING_LIST    = ARGLIST(1)(1:60)
           NSNTYPE_IGNORE = PARSE_INTLIST(STRING_LIST,SNTYPE_IGNORE)

         else if ( MATCH_NMLKEY('SNCID_LIST',  ! Aug 18 2020
     &             1, iArg, ARGLIST) ) then
           STRING_LIST = ARGLIST(1)(1:60)
           NCID_LIST   = PARSE_INTLIST(STRING_LIST,SNCID_LIST)
           if ( SNCID_LIST(1) > 0 ) then
               CUTWIN_CID(1) = 0;  CUTWIN_CID(2)=0
           endif
c - - - -
        else if ( MATCH_NMLKEY('CUTWIN_NEPOCH',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NEPOCH(1)
          READ(ARGLIST(2),*) CUTWIN_NEPOCH(2)

        else if ( MATCH_NMLKEY('CUTWIN_TRESTMIN',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TRESTMIN(1)
          READ(ARGLIST(2),*) CUTWIN_TRESTMIN(2)

        else if ( MATCH_NMLKEY('CUTWIN_TRESTMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TRESTMAX(1)
          READ(ARGLIST(2),*) CUTWIN_TRESTMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_TRESTRANGE',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TRESTRANGE(1)
          READ(ARGLIST(2),*) CUTWIN_TRESTRANGE(2)

        else if ( MATCH_NMLKEY('CUTWIN_TREST2',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TREST2(1)
          READ(ARGLIST(2),*) CUTWIN_TREST2(2)

        else if ( MATCH_NMLKEY('CUTWIN_TGAPMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TGAPMAX(1)
          READ(ARGLIST(2),*) CUTWIN_TGAPMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_T0GAPMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_T0GAPMAX(1)
          READ(ARGLIST(2),*) CUTWIN_T0GAPMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_TREST',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TREST(1)
          READ(ARGLIST(2),*) CUTWIN_TREST(2)

        else if ( MATCH_NMLKEY('CUTWIN_TOBS',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TOBS(1)
          READ(ARGLIST(2),*) CUTWIN_TOBS(2)

        else if ( MATCH_NMLKEY('CUTWIN_TOBSMIN',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TOBSMIN(1)
          READ(ARGLIST(2),*) CUTWIN_TOBSMIN(2)

        else if ( MATCH_NMLKEY('CUTWIN_TOBSMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TOBSMAX(1)
          READ(ARGLIST(2),*) CUTWIN_TOBSMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_RA',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_RA(1)
          READ(ARGLIST(2),*) CUTWIN_RA(2)

        else if ( MATCH_NMLKEY('CUTWIN_DEC',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_DEC(1)
          READ(ARGLIST(2),*) CUTWIN_DEC(2)

        else if ( MATCH_NMLKEY('CUTWIN_PEAKMJD',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_PEAKMJD(1)
          READ(ARGLIST(2),*) CUTWIN_PEAKMJD(2)

        else if ( MATCH_NMLKEY('CUTWIN_MJD',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_MJD(1)
          READ(ARGLIST(2),*) CUTWIN_MJD(2)

        else if ( MATCH_NMLKEY('CUTWIN_MJD_EXCLUDE',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_MJD_EXCLUDE(1)
          READ(ARGLIST(2),*) CUTWIN_MJD_EXCLUDE(2)

        else if ( MATCH_NMLKEY('CUTWIN_MJD_INCLUDE',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_MJD_INCLUDE(1)
          READ(ARGLIST(2),*) CUTWIN_MJD_INCLUDE(2)

        else if ( MATCH_NMLKEY('CUTWIN_REDSHIFT',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_REDSHIFT(1)
          READ(ARGLIST(2),*) CUTWIN_REDSHIFT(2)

        else if ( MATCH_NMLKEY('CUTWIN_REDSHIFT_ERR',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_REDSHIFT_ERR(1)
          READ(ARGLIST(2),*) CUTWIN_REDSHIFT_ERR(2)

        else if ( MATCH_NMLKEY('CUTWIN_HOSTSEP',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_HOSTSEP(1)
          READ(ARGLIST(2),*) CUTWIN_HOSTSEP(2)

        else if ( MATCH_NMLKEY('CUTWIN_NFILT_TRESTMIN',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NFILT_TRESTMIN(1)
          READ(ARGLIST(2),*) CUTWIN_NFILT_TRESTMIN(2)

        else if ( MATCH_NMLKEY('CUTWIN_NFILT_TRESTMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NFILT_TRESTMAX(1)
          READ(ARGLIST(2),*) CUTWIN_NFILT_TRESTMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_NFILT_TREST2',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NFILT_TREST2(1)
          READ(ARGLIST(2),*) CUTWIN_NFILT_TREST2(2)

        else if ( MATCH_NMLKEY('SNCUT_SNRMAX',
     &            1, iArg, ARGLIST) ) then
          SNCUT_SNRMAX = ARGLIST(1)(1:MXCHAR_CUTNAME)

        else if ( MATCH_NMLKEY('SNCUT_HOST_SBFLUX',
     &            1, iArg, ARGLIST) ) then
          SNCUT_HOST_SBFLUX = ARGLIST(1)(1:MXCHAR_CUTNAME)

        else if ( MATCH_NMLKEY('SIMVAR_CUTWIN_STRING',
     &            1, iArg, ARGLIST) ) then
          SIMVAR_CUTWIN_STRING = ARGLIST(1)(1:MXCHAR_CUTNAME)

        else if ( MATCH_NMLKEY('CUTWIN_NFILT_SNRMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NFILT_SNRMAX(1)
          READ(ARGLIST(2),*) CUTWIN_NFILT_SNRMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_NFILT_SNRMAX2',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NFILT_SNRMAX2(1)
          READ(ARGLIST(2),*) CUTWIN_NFILT_SNRMAX2(2)

        else if ( MATCH_NMLKEY('CUTWIN_NFIELD',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_NFIELD(1)
          READ(ARGLIST(2),*) CUTWIN_NFIELD(2)

        else if ( MATCH_NMLKEY('CUTWIN_MWEBV',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_MWEBV(1)
          READ(ARGLIST(2),*) CUTWIN_MWEBV(2)

        else if ( MATCH_NMLKEY('CUTWIN_RESTLAM',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_RESTLAM(1)
          READ(ARGLIST(2),*) CUTWIN_RESTLAM(2)
        else if ( MATCH_NMLKEY('CUTWIN_LAMREST', ! same as CUVTIN_RESTLAM
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_LAMREST(1)
          READ(ARGLIST(2),*) CUTWIN_LAMREST(2)

        else if ( MATCH_NMLKEY('CUTWIN_LAMOBS',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_LAMOBS(1)
          READ(ARGLIST(2),*) CUTWIN_LAMOBS(2)

        else if ( MATCH_NMLKEY('EPCUT_SNRMIN',
     &            1, iArg, ARGLIST) ) then
          EPCUT_SNRMIN = ARGLIST(1)(1:MXCHAR_CUTNAME)

        else if ( MATCH_NMLKEY('SNRMAX_FILTERS',
     &            1, iArg, ARGLIST) ) then
          SNRMAX_FILTERS = ARGLIST(1)(1:MXFILT_ALL)

        else if ( MATCH_NMLKEY('CUTWIN_SNRMAX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_SNRMAX(1)
          READ(ARGLIST(2),*) CUTWIN_SNRMAX(2)

        else if ( MATCH_NMLKEY('CUTWIN_SNRMAX2',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_SNRMAX2(1)
          READ(ARGLIST(2),*) CUTWIN_SNRMAX2(2)

        else if ( MATCH_NMLKEY('CUTWIN_SNR_NODETECT',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_SNR_NODETECT(1)
          READ(ARGLIST(2),*) CUTWIN_SNR_NODETECT(2)

        else if ( MATCH_NMLKEY('CUTWIN_PSF',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_PSF(1)
          READ(ARGLIST(2),*) CUTWIN_PSF(2)

        else if ( MATCH_NMLKEY('CUTWIN_ZPERR',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_ZPERR(1)
          READ(ARGLIST(2),*) CUTWIN_ZPERR(2)

        else if ( MATCH_NMLKEY('CUTWIN_PHOTPROB',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_PHOTPROB(1)
          READ(ARGLIST(2),*) CUTWIN_PHOTPROB(2)

        else if ( MATCH_NMLKEY('CUTWIN_ZPADU',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_ZPADU(1)
          READ(ARGLIST(2),*) CUTWIN_ZPADU(2)

        else if ( MATCH_NMLKEY('CUTWIN_ZPNPE',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_ZPNPE(1)
          READ(ARGLIST(2),*) CUTWIN_ZPNPE(2)

        else if ( MATCH_NMLKEY('CUTWIN_ERRTEST',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_ERRTEST(1)
          READ(ARGLIST(2),*) CUTWIN_ERRTEST(2)

        else if ( MATCH_NMLKEY('CUTWIN_SIMPULL',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_SIMPULL(1)
          READ(ARGLIST(2),*) CUTWIN_SIMPULL(2)

        else if ( MATCH_NMLKEY('CUTWIN_TREST_TRUEFLUX',
     &            2, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) CUTWIN_TREST_TRUEFLUX(1)
          READ(ARGLIST(2),*) CUTWIN_TREST_TRUEFLUX(2)

c - - - -
         else if ( MATCH_NMLKEY('MAGOBS_SHIFT_PRIMARY',
     &             1, iArg, ARGLIST) ) then
           MAGOBS_SHIFT_PRIMARY = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('MAGOBS_SHIFT_ZP',
     &             1, iArg, ARGLIST) ) then
           MAGOBS_SHIFT_ZP = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('MAGREST_SHIFT_PRIMARY',
     &             1, iArg, ARGLIST) ) then
           MAGREST_SHIFT_PRIMARY = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('MAGREST_SHIFT_ZP',
     &             1, iArg, ARGLIST) ) then
           MAGREST_SHIFT_ZP = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FILTER_LAMSHIFT',
     &             1, iArg, ARGLIST) ) then
           FILTER_LAMSHIFT = ARGLIST(1)(1:MXCHAR_CUTNAME)
c - - - - - -
        else if ( MATCH_NMLKEY('MAGOBS_SHIFT_PRIMARY_PARAMS',
     &            3, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) MAGOBS_SHIFT_PRIMARY_PARAMS(1)
          READ(ARGLIST(2),*) MAGOBS_SHIFT_PRIMARY_PARAMS(2)
          READ(ARGLIST(3),*) MAGOBS_SHIFT_PRIMARY_PARAMS(3)

        else if ( MATCH_NMLKEY('MAGOBS_SHIFT_ZP_PARAMS',
     &            3, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) MAGOBS_SHIFT_ZP_PARAMS(1)
          READ(ARGLIST(2),*) MAGOBS_SHIFT_ZP_PARAMS(2)
          READ(ARGLIST(3),*) MAGOBS_SHIFT_ZP_PARAMS(3)
c - - - - - - -
         else if ( MATCH_NMLKEY('FUDGE_FLUXCAL_OFFSET',
     &             1, iArg, ARGLIST) ) then
           FUDGE_FLUXCAL_OFFSET = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FUDGE_FLUXCAL_ERROR',
     &             1, iArg, ARGLIST) ) then
           FUDGE_FLUXCAL_ERROR = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FUDGE_FLUXCAL_ERRPIX',
     &             1, iArg, ARGLIST) ) then
           FUDGE_FLUXCAL_ERRPIX = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FUDGE_FLUXERR_SCALE',
     &             1, iArg, ARGLIST) ) then
           FUDGE_FLUXERR_SCALE = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FUDGE_MAG_ERROR',
     &             1, iArg, ARGLIST) ) then
           FUDGE_MAG_ERROR = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FUDGE_MAG_COVERR',
     &             1, iArg, ARGLIST) ) then
           FUDGE_MAG_COVERR = ARGLIST(1)(1:MXCHAR_CUTNAME)

         else if ( MATCH_NMLKEY('FUDGE_HOSTNOISE_FILE',
     &             1, iArg, ARGLIST) ) then
           FUDGE_HOSTNOISE_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('FLUXERRMODEL_FILE',
     &             1, iArg, ARGLIST) ) then
           FLUXERRMODEL_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)
         else if ( MATCH_NMLKEY('SIM_FLUXERRMODEL_FILE',
     &             1, iArg, ARGLIST) ) then
           SIM_FLUXERRMODEL_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

        else if ( MATCH_NMLKEY('FLUXERRMODEL_OPTMASK',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) FLUXERRMODEL_OPTMASK

         else if ( MATCH_NMLKEY('MAGCOR_FILE',
     &             1, iArg, ARGLIST) ) then
           MAGCOR_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

         else if ( MATCH_NMLKEY('SIM_MAGCOR_FILE',
     &             1, iArg, ARGLIST) ) then
           SIM_MAGCOR_FILE = ARGLIST(1)(1:MXCHAR_FILENAME)

c - - - - - - -
        else if ( MATCH_NMLKEY('RV_MWCOLORLAW',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) RV_MWCOLORLAW

        else if ( MATCH_NMLKEY('OPT_MWCOLORLAW',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) OPT_MWCOLORLAW

        else if ( MATCH_NMLKEY('OPT_MWEBV',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) OPT_MWEBV

        else if ( MATCH_NMLKEY('MWEBV_SCALE',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) MWEBV_SCALE

        else if ( MATCH_NMLKEY('MWEBV_SHIFT',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) MWEBV_SHIFT

        else if ( MATCH_NMLKEY('MWEBV_FORCE',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) MWEBV_FORCE

        else if ( MATCH_NMLKEY('REDSHIFT_FINAL_SHIFT',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) REDSHIFT_FINAL_SHIFT

        else if ( MATCH_NMLKEY('HOSTGAL_SPECZ_SHIFT',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) HOSTGAL_SPECZ_SHIFT

        else if ( MATCH_NMLKEY('HOSTGAL_PHOTOZ_SHIFT',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) HOSTGAL_PHOTOZ_SHIFT


        else if ( MATCH_NMLKEY('VPEC_ERR_OVERRIDE',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) VPEC_ERR_OVERRIDE

        else if ( MATCH_NMLKEY('FLUXERRCALC_ZPTERR',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) FLUXERRCALC_ZPTERR

        else if ( MATCH_NMLKEY('H0_REF',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) H0_REF

        else if ( MATCH_NMLKEY('OLAM_REF',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) OLAM_REF

        else if ( MATCH_NMLKEY('OMAT_REF',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) OMAT_REF

        else if ( MATCH_NMLKEY('W0_REF',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) W0_REF

        else if ( MATCH_NMLKEY('ZTOL_HELIO2CMB',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ZTOL_HELIO2CMB
        else if ( MATCH_NMLKEY('zZTOL_HELIO2CMB', ! same, with 'z'
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ZTOL_HELIO2CMB
c - - - -

        else if ( MATCH_NMLKEY('ABORT_ON_BADSURVEY',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_BADSURVEY

        else if ( MATCH_NMLKEY('ABORT_ON_BADFILTER',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_BADFILTER

        else if ( MATCH_NMLKEY('ABORT_ON_NOEPOCHS',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_NOEPOCHS

        else if ( MATCH_NMLKEY('ABORT_ON_NOPKMJD',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_NOPKMJD

        else if ( MATCH_NMLKEY('ABORT_ON_BADAVWARP',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_BADAVWARP

        else if ( MATCH_NMLKEY('ABORT_ON_BADKCOR',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_BADKCOR

        else if ( MATCH_NMLKEY('ABORT_ON_MARGPDF0',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_MARGPDF0

        else if ( MATCH_NMLKEY('ABORT_ON_TRESTCUT',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_TRESTCUT

        else if ( MATCH_NMLKEY('ABORT_ON_DUPLCID',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_DUPLCID

        else if ( MATCH_NMLKEY('ABORT_ON_DUPLMJD',
     &            1, iArg, ARGLIST) ) then
          READ(ARGLIST(1),*) ABORT_ON_DUPLMJD

c - - -
        endif

c ?????????????
c PROBLEM: for XYZ=5,999 iArg does not increment, and thus USE_LINE_ARGS
c          is NOT filled.
c ?????????????

c set logical flag for used LINE_ARGS
c   _LEGACY is for "KEY VAL" (space separated)
c   _REFAC  is for "KEY=VAL" (single string)

        VALID_ARGLIST = .TRUE.
        if ( ARGLIST(1) .EQ. ''     ) VALID_ARGLIST = .FALSE.
        if ( ARGLIST(1) .EQ. 'NULL' ) VALID_ARGLIST = .FALSE.

        FOUND_MATCH_LEGACY =
     &    ( iArg .GT. ilast )
        FOUND_MATCH_REFAC  =
     &    ( iArg .EQ. ilast .and. HAS_EQUAL .and. VALID_ARGLIST )

        if ( LDMP ) then
           print*,' xxx - - - - - - - - '
           print*,' xxx  LEGACY,REFAC = ',
     &          FOUND_MATCH_LEGACY, FOUND_MATCH_REFAC
           print*,' xxx  ilast, iArg = ', ilast, iArg
           print*,' xxx  ARGLIST(1)  = ', ARGLIST(1)(1:40)
        endif

         IF ( FOUND_MATCH_LEGACY .or. FOUND_MATCH_REFAC) THEN
           DO iuse = ilast, iArg
c              print*,' xxx  load USE_ARG for ', iuse
              USE_LINE_ARGS(iuse) = .TRUE.
           ENDDO
         ENDIF
         iArg = iArg + 1 ;       ilast = iArg

4444  CONTINUE

      DO_STOP = .false.
      IF ( DO_STOP ) then
         print*,' '
         print*,' xxx ------------------------------------- '
         print*,' xxx CUTWIN_SNRMAX = ', CUTWIN_SNRMAX
         print*,' xxx DEBUG STOP '
         STOP
      ENDIF

      RETURN
      END  ! end SNLCINP_OVERRIDE


C ================================================
CDECK  ID>,  MATCH_NMLKEY. 
      LOGICAL FUNCTION MATCH_NMLKEY(KEYNAME,NARG,iArg,argList)

c Created July 25 2020
c
c Example 1:
c   KEYNAME           = 'CUTWIN_SNRMAX'
c   LINE_ARGS(iArg)   = 'CUTWIN_SNRMAX'
c   LINE_ARGS(iArg+1) = '5'
c   LINE_ARGS(iArg+2) = '9999'
c   NARG    = 2
c   iArg    = iArg + 2     ! <== returned
c   ARGLIST = '5', '9999'  ! <== returned
c
c Example 2:
c   KEYNAME           = 'CUTWIN_SNRMAX'
c   LINE_ARGS(iArg)   = 'CUTWIN_SNRMAX=5,9999'
c   NARG    = 2
c   iArg    = iArg         ! <== returned unchanged
c   ARGLIST = '5', '9999'  ! <== returned
c
c ----------------------
c
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )


c+CDE,CTRLCOM.

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c function args
c MXCHAR_FILENAME
      CHARACTER KEYNAME*(*)      ! (I) keyname to check
      INTEGER   NARG             ! (I) number of arguments to check
      INTEGER   iArg             ! (I) current index for LINE_ARGS(i)
      CHARACTER ARGLIST(*)*(*)   ! (O) 'NARG' string args for KEYNAME

c local args
      INTEGER LENKEY, LENARG1_EQ, LENARG1_TOT, i
      INTEGER jcomma, jlast
      LOGICAL KEYPLUSARG_ONESTRING, LDMP
      CHARACTER ARG*(MXCHAR_ARG), ARGSTRING*(MXCHAR_ARG)

C ------------- BEGIN ------------

      MATCH_NMLKEY = .false.
      DO i = 1, NARG
         ARGLIST(i) = 'NULL'
      ENDDO
      LDMP = .false.
c      LDMP =  ( KEYNAME(1:8) .EQ. 'FITMODEL'  )

      LENKEY = INDEX(KEYNAME//' ', ' ') - 1

      CALL GETARG(iArg,ARG)
      LENARG1_EQ  = INDEX(ARG,'=') - 1
      LENARG1_TOT = INDEX(ARG,' ') - 1

      IF ( LENARG1_EQ < 0 ) THEN
         LENARG1_EQ = LENARG1_TOT
         KEYPLUSARG_ONESTRING = .false. ! e.g., CUTWIN_SNRMAX 5 999
      ELSE
         KEYPLUSARG_ONESTRING = .true. ! e.g., CUTWIN_SNRMAX=5,999
      ENDIF

      if ( LDMP ) then
        print*,' xxx --------- MATCH_NMLKEY DUMP ------------- '
        print*,' xxx  LINE_ARG  = ', ARG(1:60)
        print*,' xxx  KEYNAME   = ', KEYNAME(1:LENKEY)
        print*,' xxx  iArg,NARG = ', iArg, NARG
        print*,' xxx  LENARG1   = ', LENARG1_EQ, LENARG1_TOT
        print*,' xxx  LENKEY    = ', LENKEY
        print*,' xxx  KEYPLUSARG_ONESTRING=',KEYPLUSARG_ONESTRING
      endif

      if ( LENARG1_EQ .NE. LENKEY ) RETURN

      MATCH_NMLKEY = ( ARG(1:LENARG1_EQ) .EQ. KEYNAME(1:LENKEY) )

      IF ( .NOT. MATCH_NMLKEY ) RETURN

      IF ( KEYPLUSARG_ONESTRING ) THEN

c xxxx         ARGSTRING = LINE_ARGS(iArg)(LENARG1_EQ+2:LENARG1_TOT)
         ARGSTRING = ARG(LENARG1_EQ+2:LENARG1_TOT)

c break comma-sep ARGSTRING into sub strings
         jlast = 1
         DO i = 1, NARG
           if ( i .EQ. NARG ) then
               ARGLIST(i) = ARGSTRING(jlast:LENARG1_TOT)
            else
               jcomma     = INDEX(ARGSTRING,',') - 1
               ARGLIST(i) = ARGSTRING(jlast:jcomma)
               jlast      = jcomma + 2
            endif
         ENDDO
      ELSE
         DO i = 1, NARG
           iArg = iArg + 1
           CALL GETARG(iArg, ARG)
           ARGLIST(i) = ARG   ! xxx LINE_ARGS(iArg)
         ENDDO
      ENDIF

      if ( LDMP ) then
        do i = 1, NARG
           write(6,38) i, arglist(i)(1:40)
38         format(T10,' xxx out argList(',I2,') = ', A )
        enddo
      endif

      RETURN
      END    ! end MATCH_NMLKEY


C ========================================
CDECK  ID>,  MCMCINP_OVERRIDE. 
      SUBROUTINE MCMCINP_OVERRIDE(IERR)

c Created Dec 4, 2009 R.Kessler
c
c Check command-line args for user-option to override
c &MCMCINP namelist values.
c
c ----------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,MCMCCOM. inserted below by ypatchy. 

c Created Nov 2009 for Ben Dilday's  MCMC method

c a bunch of MCMC stuff
      LOGICAL LMCMC
     &  ,LTUP_MCMC    ! book/fill special ntuple

      INTEGER
     &   NMCMC_EVAL        ! number of total evaluations for MCMC
     &  ,IMCMC_FLAG        ! a generic flag for MCMC variations
     &  ,NMCMC_CHAINS      ! number of chains to run
     &  ,NMCMC_BURN        ! size of burn in
     &  ,IMCMC_STORE       ! store every nth chi2 in the ntuple

      CHARACTER
     &  CHOPT_MCMC*16     ! ??

      REAL
     &   MCMC_NSIG_STEP   ! ??
     &  ,NSIG_MCMC_START  ! ??

      COMMON / SNFMCMC / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN,MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START

      NAMELIST / MCMCINP / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN, MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START


C =============================================
      INTEGER IERR ! (O) 0 => OK
c local var
      INTEGER  i, ilast, iuse
C -------------- BEGIN --------------
      IERR = 0
      i = 2
      ilast = 2
      DO WHILE ( i .LT. NLINE_ARGS )
cc xxxxx

c set logical flag for used LINE_ARGS
         IF ( i .GT. ilast ) THEN
           DO iuse = ilast, i
              USE_LINE_ARGS(iuse) = .TRUE.
           ENDDO
         ENDIF
         i = i + 1
         ilast = i
      ENDDO

      RETURN
      END   ! end of MCMCINP_OVERRIDE


C ========================================
CDECK  ID>,  NNINP_OVERRIDE. 
      SUBROUTINE NNINP_OVERRIDE()

c Created Apr 23, 2014 R.Kessler
c
c Check command-line args for user-option to override
c &NNINP namelist values.
c
c ----------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


c local var
      INTEGER  i, LL, ilast, iuse
      CHARACTER INPUT_ARG*(MXCHAR_ARG)
      CHARACTER ARGLIST(MXKEY_ARGS)*(MXCHAR_ARG)
      LOGICAL   MATCH_NMLKEY

C -------------- BEGIN --------------

      i = 2
      ilast = 2

      DO WHILE ( i .LT. NLINE_ARGS )

        CALL GETARG(i, INPUT_ARG )  ! read command-line args

         LL = INDEX ( INPUT_ARG, ' ' ) - 1

        if ( MATCH_NMLKEY('NEARNBR_TRAINFILE_PATH',
     &            1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_TRAINFILE_PATH

        else if ( MATCH_NMLKEY('NEARNBR_TRAINFILE_LIST',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_TRAINFILE_LIST

        else if ( MATCH_NMLKEY('NEARNBR_TRAINFILE_SCALE_NON1A',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_TRAINFILE_SCALE_NON1A

        else if ( MATCH_NMLKEY('NEARNBR_SEPMAX_VARDEF',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_SEPMAX_VARDEF

        else if ( MATCH_NMLKEY('NEARNBR_TRUETYPE_VARNAME',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_TRUETYPE_VARNAME

        else if ( MATCH_NMLKEY('NEARNBR_TRAIN_ODDEVEN',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_TRAIN_ODDEVEN

        else if ( MATCH_NMLKEY('NEARNBR_SEPMAX_IGNORE',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NEARNBR_SEPMAX_IGNORE

        else if ( MATCH_NMLKEY('NN_ITYPE_FIX',
     &             1, i, ARGLIST) ) then
           READ(ARGLIST(1),*) NN_ITYPE_FIX

         endif



c set logical flag for used LINE_ARGS

         IF ( i .GT. ilast ) THEN
           DO iuse = ilast, i
              USE_LINE_ARGS(iuse) = .TRUE.
           ENDDO
         ENDIF

         i = i + 1
         ilast = i

      ENDDO

      RETURN
      END


C ==================================
CDECK  ID>,  PROCSNNML. 
      SUBROUTINE PROCSNNML(IERR)
c
c Created May 17, 2008 by R.Kessler
c
c Translate namelist strings that depend on filters
c into cutwin_*filt(2,filt) variables.
c
c Must call after first event is read so that filters are defined.
c Note that RDKCOR is not called yet.
c
c
c Aug 31, 2010:
c  - set new variables  NFILT_SNRMAX & IFILT_SNRMAX(i=1,NFILT_SNRMAX)
c  - CUTWIN_SNRMAX_FILT now depends on sparse ifilt_SNRMAX index
c
c Nov 15, 2011: new variables FUDGE_FLUXCAL_[OFFSET,ERROR]
c
c Mar 06, 2012: parse new variable SNCUT_HOST_SBFLUX
c Apr 02, 2014: parse SNRMAX_FILTERS, set LFILTDEF_SNRMAX
c Dec 16, 2018: parse SIMVAR_CUTWIN_STRING
c -----------------------------

      IMPLICIT NONE

      INTEGER IERR

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IAFILT(MXFILT_OBS)
      REAL    XAFILT(MXFILT_OBS)

      INTEGER ifiltdef, NF, i, ifilt, ifiltinv
      CHARACTER cfilt*2
      REAL TMP_ZP, TMP_PRIM
      LOGICAL LDMP, LTMP

c function
      INTEGER FILTINDX

C ---------------- BEGIN -------------

      IERR = 0
      CALL PARSE_FILTSTRING(1,SNCUT_SNRMAX, NF, iafilt, xafilt )
      NFILT_SNRMAX = NF
      if ( NFILT_SNRMAX .GT. MXFILT_SNRMAX ) then
         write(c1err,661) NFILT_SNRMAX, MXFILT_SNRMAX
661      format(I2,' SNRMAX cuts exceeds bound of MXFILT_SNRMAX=',I2)
         c2err = 'Check &SNLCINP variable SNCUT_SNRMAX'
         CALL  MADABORT("PROCSNNML", C1ERR, C2ERR)
      endif


      DO i = 1, NF
         ifiltdef = IAFILT(i)
         ifilt    = IFILTDEF_INVMAP_SURVEY(ifiltdef)
         cutwin_snrmax_filt(1,i) = xafilt(i) ! Aug 31, 2010
         ifilt_SNRMAX(i)         = ifiltdef  ! Aug 31, 2010
      ENDDO

c -------

      CALL PARSE_FILTSTRING(1,SNCUT_HOST_SBFLUX, NF, iafilt, xafilt )
      NFILT_HOST_SBFLUX = NF
      if ( NF .GT. MXFILT_SNRMAX ) then
         write(c1err,662) NFILT_HOST_SBFLUX, MXFILT_SNRMAX
662      format(I2,' HOST_SBFLUX cuts exceeds bound of ',I2)
         c2err = 'Check &SNLCINP variable SNCUT_SNRMAX'
         CALL  MADABORT("PROCSNNML", C1ERR, C2ERR)
      endif

      DO i = 1, NF
         ifiltdef = IAFILT(i)
         ifilt    = IFILTDEF_INVMAP_SURVEY(ifiltdef)
         cutwin_sbflux_filt(1,i) = xafilt(i)
         ifilt_HOST_SBFLUX(i)    = ifiltdef
      ENDDO

c ----------

      CALL PARSE_FILTSTRING(1,EPCUT_SNRMIN, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         ifilt    = IFILTDEF_INVMAP_SURVEY(ifiltdef)
         cutwin_snrmin_filt(1,ifilt) = xafilt(i)
      ENDDO

c ------
      CALL PARSE_FILTSTRING(0, MAGOBS_SHIFT_PRIMARY, NF,iafilt,xafilt)
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         magobs_shift_primary_filt(ifiltdef) = xafilt(i)
      ENDDO

      CALL PARSE_FILTSTRING(1,MAGOBS_SHIFT_ZP, NF, iafilt, xafilt)
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         magobs_shift_zp_filt(ifiltdef) = xafilt(i)
         magobs_shift_zp_user(ifiltdef) = xafilt(i)
      ENDDO

c ---
      CALL PARSE_FILTSTRING(1,FUDGE_FLUXCAL_OFFSET, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FUDGE_FLUXCAL_OFFSET_FILT(ifiltdef) = xafilt(i)
      ENDDO

c - - - -
      CALL PARSE_FILTSTRING(1,FUDGE_FLUXCAL_ERROR, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FUDGE_FLUXCAL_ERROR_FILT(ifiltdef) = xafilt(i)
      ENDDO

      CALL PARSE_FILTSTRING(1,FUDGE_FLUXCAL_ERRPIX, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FUDGE_FLUXCAL_ERRPIX_FILT(ifiltdef) = xafilt(i)
      ENDDO

      CALL PARSE_FILTSTRING(1,FUDGE_FLUXERR_SCALE, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FUDGE_FLUXERR_SCALE_FILT(ifiltdef) = xafilt(i)
      ENDDO

c - - -

      CALL PARSE_FILTSTRING(1,FUDGE_MAG_ERROR, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FUDGE_MAG_ERROR_FILT(ifiltdef) = xafilt(i)
      ENDDO

      CALL PARSE_FILTSTRING(1,FUDGE_MAG_COVERR, NF, iafilt, xafilt )
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FUDGE_MAG_COVERR_FILT(ifiltdef) = xafilt(i)
      ENDDO

c --- REST FRAME
      CALL PARSE_FILTSTRING(0, MAGREST_SHIFT_PRIMARY, NF,iafilt,xafilt)
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         magrest_shift_primary_filt(ifiltdef) = xafilt(i)
      ENDDO

      CALL PARSE_FILTSTRING(1,MAGREST_SHIFT_ZP, NF, iafilt, xafilt)
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         magrest_shift_zp_filt(ifiltdef) = xafilt(i)
         magrest_shift_zp_user(ifiltdef) = xafilt(i)
      ENDDO

      CALL PARSE_FILTSTRING(1,FILTER_LAMSHIFT, NF, iafilt, xafilt)
      DO i = 1, NF
         ifiltdef = IAFILT(i)
         FILTER_LAMSHIFT_FILT(ifiltdef) = xafilt(i)
      ENDDO

c ------
      LDMP = .FALSE.

      do ifiltdef  = 1, MXFILT_ALL
         cfilt     = filtdef_string(ifiltdef:ifiltdef)
         tmp_zp    = MAGOBS_SHIFT_ZP_FILT(ifiltdef)
         tmp_prim  = MAGOBS_SHIFT_PRIMARY_FILT(ifiltdef)

         LTMP = ( tmp_zp .ne. 0.0 .or. tmp_prim .NE. 0.0 )
         if ( LDMP .and. LTMP ) then
           print*, 'DBUG: ', cfilt, ifiltdef
     &      , ' : MAGSHIFT_[ZP,PRIMARY] = ', tmp_zp, tmp_prim
         endif
      enddo

c -------
      NF = INDEX(SNRMAX_FILTERS,' ') - 1

      IF ( NF > 0 ) THEN

        do ifilt = 1, MXFILT_ALL
           LFILTDEF_SNRMAX(ifilt) = .FALSE.
        enddo
        do ifilt = 1, NF
           cfilt = SNRMAX_FILTERS(ifilt:ifilt)
           IFILTDEF = FILTINDX(cfilt)
           ifiltinv = IFILTDEF_INVMAP_SURVEY(ifiltdef)
           if ( ifiltinv < 1 ) then
              C1ERR = 'Invalid filter = ' // Cfilt
              C2err = 'Check &SNLCINP variable SNRMAX_FILTERS = '
     &                   // SNRMAX_FILTERS(1:NF)
              CALL  MADABORT("PROCSNNML", C1ERR, C2ERR)
           endif
           LFILTDEF_SNRMAX(ifiltdef) = .TRUE.
        enddo

      ENDIF


c ------------------------------------------------------------
c Dec 2018: check for cuts on SIMVAR (e.g., SIM_c, SIM_ZCMB)

      CALL PARSE_SIMVAR_CUTS()

c Jan 12 2021: check option to fix sign VPEC for older data
      DOFIX_WRONG_SIGN_VPEC = (.not. RESTORE_WRONG_VPEC ) .and.
     &                        (.not. ISCORRECT_SIGN_VPEC)
      if ( DOFIX_WRONG_SIGN_VPEC ) then
         print*,' '
         print*,'    *** ALERT: VPEC sign will be flipped *** '
         print*,' '
      endif

      if ( RESTORE_WRONG_VPEC ) then
         print*,' '
         print*,'    *** ALERT: use wrong VPEC formula *** '
         print*,' '
      endif

         CALL FLUSH(6)

c set flag for systematic zshift (Jun 2021)
      DOzSHIFT =
     &    ( REDSHIFT_FINAL_SHIFT .NE. 0.0 ) .or.
     &    ( HOSTGAL_SPECZ_SHIFT  .NE. 0.0 ) .or.
     &    ( HOSTGAL_PHOTOZ_SHIFT .NE. 0.0 )

      RETURN
      END  ! end PROCSNNML


C ==================================
CDECK  ID>,  RDSNIGNORE. 
      SUBROUTINE RDSNIGNORE
c
c Nov 10, 2008
c Read file SNCID_IGNORE_FILE and load logical array LSNCID_IGNORE
c This is designed for the thousands of SDSS-II candidates,
c so that large numbers of candidates can be ignored from a
c list file.
c
c Sep 2 2019: allow up to MXIGNORE_LIST=500 (instead of 52)
c Sep 10 2021:
c   + fix to work properly with/without DOCANA
c   + ignore comments
c   + print first/last CID for visual crosscheck
c
c --------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER CCID*(MXCHAR_CCID), cFILE*(MXCHAR_FILENAME), FNAM*12
      CHARACTER WD1*40
      INTEGER MSKOPT, i, LENFILE, LENCID, NWD, FLAG_DOCANA
      INTEGER NSTORE, NCCID_IGNORE_ORIG
      LOGICAL FOUND_DOCANA, FOUND_DOCANA_END, LREQUIRE_DOCANA

      INTEGER  STORE_PARSE_WORDS, ISTAT_FILE_DOCANA
      EXTERNAL STORE_PARSE_WORDS, REACT_MISSING_DOCANA
C ------------- BEGIN ---------

      IF ( SNCID_IGNORE_FILE .EQ. ' ' ) RETURN

      FNAM = 'RDSNIGNORE'
      CALL ENVreplace(SNCID_IGNORE_FILE)
      LENFILE   = INDEX(SNCID_IGNORE_FILE,' ') - 1
      cFILE     = SNCID_IGNORE_FILE(1:LENFILE)//char(0)
      MSKOPT    = MSKOPT_PARSE_WORDS_FILE
     &          + MSKOPT_PARSE_WORDS_IGNORECOMMENT
      NWD = STORE_PARSE_WORDS(MSKOPT, cFILE, FNAM//char(0), LENFILE, 12)

      LENCID = INDEX(CCID,' ')-1

c check if 1st word is DOCANA key
      CALL get_PARSE_WORD_fortran(1, WD1, LENCID)
      FOUND_DOCANA     = ( WD1 .EQ. 'DOCUMENTATION:' )
      FOUND_DOCANA_END = (.FALSE.)
      LREQUIRE_DOCANA  = (REQUIRE_DOCANA > 0 )

      if ( .NOT. FOUND_DOCANA ) then
         CALL REACT_MISSING_DOCANA(LREQUIRE_DOCANA,cFILE,LENFILE)
      endif

      NSTORE = 0
      NCCID_IGNORE_ORIG = NCCID_IGNORE !might include CIDs from elsewhere

c - - - - - -
      DO 200 i = 1, NWD
         CALL get_PARSE_WORD_fortran(i, CCID, LENCID)

         IF ( FOUND_DOCANA .and. .NOT. FOUND_DOCANA_END) THEN
            FLAG_DOCANA = ISTAT_FILE_DOCANA(i,CCID)
            IF ( FLAG_DOCANA==FLAG_DOCANA_END ) FOUND_DOCANA_END=.TRUE.
            goto 200
         ENDIF

         NSTORE       = NSTORE + 1
         NCCID_IGNORE = NCCID_IGNORE + 1
         SNCCID_IGNORE_ALL(NCCID_IGNORE) = CCID

         IF ( NCCID_IGNORE > MXIGNORE_LIST ) then
           write(c1err,661 ) NCCID_IGNORE
           write(c2err,662 ) MXIGNORE_LIST
           CALL  MADABORT(FNAM, C1ERR, C2ERR)
         endif
661        format('NCCID_IGNORE=',I4,' exceeds bound.')
662        format('Check limit MXIGNORE_LIST = ', I4 )

200   CONTINUE

      CALL PRBANNER(FNAM)
      print*,' Loaded ', NCCID_IGNORE,' IGNORE-candidates from '
      print*, '  ', SNCID_IGNORE_FILE(1:LENFILE)
      print*,'  First IGNORED CID: ',
     &     SNCCID_IGNORE_ALL(NCCID_IGNORE_ORIG+1)
      if ( NSTORE > 1 ) then
        print*,'  Last  IGNORED CID: ',
     &     SNCCID_IGNORE_ALL(NCCID_IGNORE)
      endif
      print*,' '

      RETURN
      END


C ====================================
CDECK  ID>,  ISTAT_FILE_DOCANA. 
      INTEGER FUNCTION ISTAT_FILE_DOCANA(iwd,string)

c use this utility for files where DOCANA keys break the
c file structure (e.g., SNCID_IGNORE_FILE). This utility
c easily enables skipping the DOCANA stuff.
c
c   Returns  1 if STRING = 'DOCUMENTATION:'
c   Returns  2 if STRING = 'DOCUMENTATION_END:'
c   Returns -1 if first word is not 'DOCUMENTATION:'
c        (this flags calling function to abort)
c
c - - - - -

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



      INTEGER   IWD          ! (I) word number in file
      CHARACTER STRING*(*)   ! (I)  string to check for DOCANA keys
c ---------- BEGIN -----------

      ISTAT_FILE_DOCANA = 0
      if ( STRING .EQ. 'DOCUMENTATION:'    ) then
         ISTAT_FILE_DOCANA = FLAG_DOCANA_START
       endif
       if ( STRING .EQ. 'DOCUMENTATION_END:'    ) then
          ISTAT_FILE_DOCANA = FLAG_DOCANA_END
       endif

      if (IWD==1 .and. ISTAT_FILE_DOCANA.NE.FLAG_DOCANA_START) then
         ISTAT_FILE_DOCANA = FLAG_DOCANA_ERROR
      endif

      RETURN
      END

C ====================================
CDECK  ID>,  PRBANNER. 
      SUBROUTINE PRBANNER ( banner )
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST

      character banner*(*)

      if ( .NOT. REDUCE_STDOUT_BATCH ) print*,' '
      print*,
     &   ' ######################################################## '
      print*,'   ', BANNER

      print*,
     &   ' ######################################################## '

      if ( .NOT. REDUCE_STDOUT_BATCH ) print*,' '
      CALL FLUSH(6)

      RETURN
      END

C ========================================
CDECK  ID>,  PR_SNSTATS. 
      SUBROUTINE PRINT_SNSTATS
c
c Print SN stats : reaad and passing cuts.
c If no SN pass cuts, list cut(s) that always fail.
c
c Get <z> and RMS from hid 11
c
c Apr 26, 2017: I6 -> I7 in format 48.

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      integer icut, i,  JDIFF
      LOGICAL LTEST, LFAIL

      REAL Tsn, Ttot, f_dupl
      EXTERNAL PRINT_CPUTIME

C ------------ BEGIN --------------

      global_banner = 'Job Summary '
      CALL PRBANNER ( GLOBAL_BANNER )

c ----------------------------------------------
c Start with Npasscut vs. ICUT, and for each type.
      CALL PRINT_NPASSCUTS()

c Aug 7 2020: for batch job, write stats to separate YAML file for easy parsing
      CALL PRINT_JOBSPLIT_OUT()

c ------------------------
      write(6,48) N_SNLC_CUTS, N_SNLC_PROC
48    format(/,T5,'Finished processing ',I7,
     &   ' SN after snana  cuts',
     &    3x,'(',I7,' before cuts)'  )
      CALL FLUSH(6)

c Oct 21, 2010: skip other "NEVER FOUND" message if CID cut always fails
      IF ( NACCEPT_CID .EQ. 0 ) GOTO 600

c check for valid SNTYPES (Jul 2012)
      LFAIL = NSNTYPE_LIST .GT. 0 .and. NACCEPT_TYPE .LE. 0
      IF ( LFAIL ) THEN
         print*,' '
         print*,' WARNING-SNTYPE: ',
     &       'NEVER FOUND A VALID SNTYPE ?!?!?! '
         print*,' WARNING-SNTYPE: Check nml variable SNTYPE_LIST = ',
     &        SNTYPE_LIST(1), SNTYPE_LIST(2)
         print*,' '
      ENDIF



c print fit-cut stats
      if ( N_SNLC_FIT .GT. 0 ) then
        write(6,49) N_SNLC_FITCUTS
49      format(T5,'Finished processing ',I6,
     &   ' SN after fitter cuts' )
      endif

c if no supernova pass cuts, look for cuts that always fail.

         print*,' '

600   CONTINUE

      IF ( NACCEPT_CID .EQ. 0 ) THEN
         write(6,66)  CUTBIT_CID, 'CID'
         print*,'     check CUTWIN_CID and SNCID_LIST in &SNLCINP'

      ELSE IF  ( N_SNLC_CUTS .EQ. 0 ) THEN
        DO icut = 1, CUTBIT_MJD_MARKER
          LTEST = BTEST ( CUTMASK8_SN_ALL , icut-1 )
          if ( LTEST .and. NACCEPT_CUT(icut) .EQ. 0 ) then
             i = INDEX(cutvar_name(icut), ':' )
             write(6,66) icut, cutvar_name(icut)(1:i-1)
          endif
        ENDDO
      ENDIF
66    FORMAT(T5,'** WARNING ** EVERY SN FAILS CUTBIT ', I3,
     &       ' :  ', A )

c -----------------------------------

cc      write(6,170) NEPOCH_BADPHOT_SUM, NEPOCH_USE
      write(6,170) NEPOCH_BADPHOT_SUM, NEPOCH_TOT
170   format(T5,'Bad PHOTOMETRY FLAG for ',I8,' of ', I8,' epochs')

      print*,' '
c -------------------------------------------------
c print out processing time, and process time per SN.


      CALL PRINT_CPUTIME(JTIME_LOOPSTART,
     &        "CPUTIME_PROCESS_ALL"//char(0),
     &        "minute"//char(0), 0,    20,20)

      CALL PRINT_CPUTIME(JTIME_LOOPSTART,
     &        "CPUTIME_PROCESS_RATE"//char(0),
     &        "second"//char(0), N_SNLC_CUTS,    20,20)

c --------------------------
c print DUPLICATE-CID WARNING

      IF ( N_DUPLICATE_CID > 0 ) THEN
         f_dupl = float(N_DUPLICATE_CID)/ float(N_SNLC_PROC)
         write(6,60)
         write(6,60)
         write(6,606) N_DUPLICATE_CID, 100.*f_dupl
         write(6,60)
         write(6,60)
 606     format(/, T5,'SEVERE WARNING: rejected ',I4,' Duplicate CIDs',
     &          3x,'(',F6.2,'%)', / )
      ENDIF

60      format(T2, 32('@-') )

c print DUPLICATE-MJD WARNING
      IF ( N_DUPLICATE_MJD > 0 ) THEN
         f_dupl = float(N_DUPLICATE_MJD)/ float(NEPOCH_USE)
         write(6,60)
         write(6,60)
         write(6,616) N_DUPLICATE_MJD, 100.*f_dupl
         write(6,617) NSTORE_DUPLICATE_MJD
         write(6,60)
         write(6,60)
         call flush(6)
 616     format(/,T5,'SEVERE WARNING: FOUND ',I4,' Duplicate MJD+BAND',
     &          3x,'(',F6.3,'%)' )
 617     format(T20,I4,' Duplicate MJDs are unique', /)
      ENDIF

      IF ( OPT_TABLE(ITABLE_OUTLIER) > 0 ) THEN
         CALL PRINT_OUTLIER_SUMMARY()  ! Mar 2021
      ENDIF

      RETURN
      END   ! end PRINT_SNSTATS


C =======================
CDECK  ID>,  PRNCUTS. 
      SUBROUTINE PRINT_NPASSCUTS()

c
c Jan 3, 2013
c
c Print Number of SN passing each incremental cut, and for each type.
c Table has up to 6 types, if more then make new table so that
c table does not exceed 80 columns.
c
c Feb 22, 2013: fix to work for TYPE=0
c
c For ITYPE=-1, write string 'ALL' to be more clear about meaning.
c
c Jun 19 2019: incluce ROWKEY = "CUTSTAT:" to make log file parsable.
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      LOGICAL USETYPE(-1:MXTYPE), LPRIN

      INTEGER
     &   ITYPE, NTYPE, ITYPE_LIST(MXTYPE)
     &  ,I1, I2, i, icut
     &  ,NTYPE_PER_TABLE
     &  ,N, NLAST, jcolon

      CHARACTER CUTNAME*28, ROWKEY*8

C ------------- BEGIN -------------

c first get list of used TYPES
      NTYPE = 0
      DO itype = -1, MXTYPE
        USETYPE(itype) = .FALSE.
        if (  NPASSCUT_INCREMENT(itype,1) .GT. 0 )  then
           USETYPE(itype) = .TRUE.
           NTYPE =  NTYPE + 1
           ITYPE_LIST(NTYPE) = ITYPE
        endif
      ENDDO

c print table header

      ROWKEY = "CUTSTAT:"

      print*,'                         ',
     &      'Number of SN passing incremental cut for'

      NTYPE_PER_TABLE = 6
      DO  777 I1 = 1, NTYPE, NTYPE_PER_TABLE

        write(6,20) ROWKEY, 'CUT-NAME      ITYPE='
20      format(A, 2x, A20, $)

        I2   = MIN(I1+NTYPE_PER_TABLE-1,NTYPE)
        DO i = I1, I2
           itype = ITYPE_LIST(i)

           if ( itype .EQ. -1 ) then
              write(6,27) 'ALL'
           else
              write(6,28) ITYPE
           endif
 27        format(A8,$)
 28        format(I8,$)
        ENDDO
        print*,' '
        write(6,80)
80      format(T2,  72('-') )


        DO 888 ICUT = 1, NCUTBIT_SNLC

           if(.NOT.LSIM_SNANA .and. icut.EQ.CUTBIT_SEARCH ) goto 888

c print line if any entry has a change in NPASSCUT
           LPRIN = .FALSE.
           IF ( ICUT .EQ. 1 ) THEN
              LPRIN = .TRUE.
           ELSE
              DO i = I1, I2
                itype = ITYPE_LIST(i)
                NLAST = NPASSCUT_INCREMENT(itype,icut-1)
                N     = NPASSCUT_INCREMENT(itype,icut)
                if ( N .LT. NLAST ) LPRIN = .TRUE.
              ENDDO
           ENDIF
           IF ( LPRIN ) THEN
              jcolon    = INDEX(cutvar_name(icut), ':' )
              CUTNAME   = CUTVAR_NAME(icut)(1:jcolon-1) ! remove ':'
              write(6,20) ROWKEY, CUTNAME
              DO i = I1, I2
                itype = ITYPE_LIST(i)
                write(6,28) NPASSCUT_INCREMENT(itype,icut)
              ENDDO
              print*,' '
           ENDIF
888     CONTINUE

c for fit, write number passing fit cuts.

        IF ( NFIT_ITERATION > 0 ) THEN
            CUTNAME = 'FIT+CUTS'
            write(6,20) ROWKEY, CUTNAME
            DO i = I1, I2
               itype = ITYPE_LIST(i)
               write(6,28) NPASSCUT_FIT(itype)
            ENDDO
        ENDIF
              print*,' '
              print*,' '
777   CONTINUE

      write(6,80)
      RETURN
      END

C =========================
CDECK  ID>,  PR_CPU_REMAIN. 
      SUBROUTINE PRINT_CPU_REMAIN(ISN)
C
C Created Apr 4 2024
C Print fraction of total events processed, elapsed time,
C and estimate time remaining:
C
C   Processed ~12% of events in mm minutes -> mm minutes remaining.
C
C Used only for BATCH mode.
C ----------------

      IMPLICIT NONE

      INTEGER ISN  ! (I) integer index (1-NSN)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER NSN_TOT, JTIME, JTDIF, PERCENT
      REAL FRAC, T_ELAPSE, T_REMAIN
C ------------ BEGIN ---------

      if ( .NOT. STDOUT_UPDATE ) RETURN

c bail for subset option for which this update makes no sense
      if ( .NOT. ISJOB_BATCH     ) RETURN
      if ( NCID_LIST > 0         ) RETURN
      if ( MXEVT_PROCESS < 10000 ) RETURN

      NSN_TOT = N_SNLC_READ(1)
      FRAC = FLOAT(ISN) / FLOAT(NSN_TOT)
      PERCENT = INT(FRAC*100.0 + 0.5)

      JTIME = TIME()
      JTDIF = JTIME - JTIME_LOOPSTART
      T_ELAPSE = FLOAT(JTDIF)/60.0
      T_REMAIN = T_ELAPSE * ( 1.0/FRAC - 1.0 )  ! prediction

      if ( T_ELAPSE < 1.0 ) RETURN  ! avoid printing crazy predictions

      write(6,20) PERCENT, T_ELAPSE, T_REMAIN
20    format(T6,'Processed ', I3,'% of events in ',
     &     F6.1, ' minutes -> ', F6.1,' minutes remaining.')
      call flush(6)

      RETURN
      END   ! end of PRINT_CPU_REMAIN

C ==================================
CDECK  ID>,  PRINT_JOBSPLIT_OUT. 
      SUBROUTINE PRINT_JOBSPLIT_OUT()

c Created Aug 7 2020
c If snana job is submitted by batch job (i.e., JOBSPLIT is set),
c create supplmental output file
c    [VERSION].YAML
c and write stats for batch process to read.
c This YAML file avoids submit_batch script having to parse
c potentially large log files. Also note that ABORT_IF_ZERO
c is a standard key telling batch script to ABORT if its
c value is zero; this avoids the batch script having to know
c program-specific keys for NEVT_what?
c
c Oct 12 2020: check OPT_YAML
c Jul 08 2021: write N_SNHOST_ZSPEC[ZPHOT]

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER LEN, JDIFF, AIZ
      REAL    T_CPU
      CHARACTER OUTFILE*(MXCHAR_FILENAME)

C ------------- BEGIN -------------

c if user does NOT request YAML file, then check default
c to create YAML file only if this is a batch job.

      IF ( OPT_YAML <= 0 ) THEN
        IF ( .NOT. ISJOB_BATCH       ) RETURN
        IF ( TEXTFILE_PREFIX .EQ. '' ) RETURN
      ENDIF

c write [REPFIX].YAML file...

      LEN     = INDEX(TEXTFILE_PREFIX,' ' ) - 1
      OUTFILE = TEXTFILE_PREFIX(1:LEN) // '.YAML'

c if TEXTFILE_PREFIX is not defined, then use VERSION_PHOTOMETRY
      if ( LEN == 0 ) then
         LEN = INDEX(VERSION_PHOTOMETRY(1),' ') - 1
         OUTFILE = VERSION_PHOTOMETRY(1)(1:LEN) // '.YAML'
      endif

      write(6,40) OUTFILE(1:LEN+5)
40    format(' Write stats to YAML output: ', A )

      OPEN(   UNIT   = LUNDAT
     &      , FILE   = OUTFILE
     &      , STATUS = 'UNKNOWN'
     &           )

      JDIFF = JTIME_LOOPEND - JTIME_LOOPSTART
      T_CPU = float(JDIFF)/60.

      write(LUNDAT,19) 'SURVEY:          ', SURVEY_NAME
      write(LUNDAT,19) 'FILTERS:         ',
     &       SURVEY_FILTERS(1:NFILTDEF_SURVEY)
      write(LUNDAT,20) 'IDSURVEY:        ', IDSURVEY
      write(LUNDAT,20) 'NEVT_TOT:        ', N_SNLC_PROC
      write(LUNDAT,20) 'NEVT_LC_CUTS:    ', N_SNLC_CUTS

      write(LUNDAT,20) 'NEVT_HOST_ZSPEC: ', N_SNHOST_ZSPEC
      write(LUNDAT,20) 'NEVT_HOST_ZPHOT: ', N_SNHOST_ZPHOT
      write(LUNDAT,20) 'NEVT_SPECTRA: ',    N_SNLC_SPEC ! nevt with spectra

      write(LUNDAT,20) 'NEVT_LCFIT_CUTS: ', N_SNLC_FITCUTS
      write(LUNDAT,21) 'CPU_MINUTES:     ', T_CPU
19    format(A, A)
20    format(A, I8)
21    format(A, F8.2)

c check options for ABORT_IF_ZERO (AIZ)

      AIZ = N_SNLC_FITCUTS
      IF ( MXEVT_CUTS < 10 ) AIZ = N_SNLC_CUTS

      write(LUNDAT,20) 'ABORT_IF_ZERO:   ', AIZ

      CLOSE ( UNIT = LUNDAT )

      RETURN
      END
C ======================================
CDECK  ID>,  SNANA_DRIVER. 
      SUBROUTINE SNANA_DRIVER(ISN_ALL, ISN_PROC)

c Created May 18, 2012 by R.Kessler
c
c Analysis driver for SN with
c   ISN_ALL  = absolute index for all events, regardless of cuts
c   ISN_PROC = sparse index of processed events (after cuts)
C
c Move code from MAIN to here so that each SN is fit
c right after it is read.
c
c Jun 21 2018:
c   if ERRFLAG_FIT > 0 on any iteraton, REJECT fit immediately
c   See REJECT_FIT logical.
c
c ----------------------

      IMPLICIT NONE

      INTEGER ISN_ALL, ISN_PROC  ! (I)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNCONTCM. inserted below by ypatchy. 

      INTEGER  MXPLOT_CONT, MXBIN_CONT
      PARAMETER (
     &   MXPLOT_CONT  = 5    ! max number of contour plots per SN
     &  ,MXBIN_CONT   = 100  ! max number of contour bins
     &     )

c define arrays to hold MNCONT informatino for contour plots

      INTEGER
     &   NPLOT_CONT                 ! number of user-contour plots
     &  ,HID_CONT(2,MXPLOT_CONT)    ! store hbook ids for vectors
     &  ,IPAR_CONT(2,MXPLOT_CONT)   ! stores which IPAR for contours
     &  ,NPT_CONT(MXPLOT_CONT)      ! stores Npt per contour plot
     &  ,NPT_FOUND(MXPLOT_CONT)

      REAL*8
     &   VCONT8(MXBIN_CONT,2,MXPLOT_CONT)  ! vector array for IPAR1

      COMMON / CONTOURCOM4 / NPLOT_CONT
     &   ,HID_CONT, IPAR_CONT, NPT_CONT, NPT_FOUND

      COMMON / CONTOURCOM8 /  VCONT8



C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


      INTEGER NCALL_MNFIT, ITER
      LOGICAL LAST_ITER, REJECT_FIT

      INTEGER IERR
      REAL*8  PS8
      LOGICAL REJECT_PRESCALE, USE_MINOS_LOCAL
      CHARACTER FNAM*14

c ----------------- BEGIN -------------

      FNAM = 'SNANA_DRIVER'

      if ( ISN_PROC > MXSNLC-1 ) THEN
        write(c1err,666) N_SNLC_PROC
666     format('ISN_PROC=',I8,' exceeds MXSNLC array bound.')
        c2err = 'Try splitting job into multiple jobs with CID-ranges'
        CALL MADABORT(FNAM, c1err, c2err)
      endif

      if ( LSIM_SNANA ) THEN
         PS8 = DBLE(SIM_PRESCALE)
         if ( REJECT_PRESCALE(N_SNLC_PROC,PS8) ) RETURN

c Apr 2019: special NNtrain option to pick only EVEN CID
         if ( NEARNBR_TRAIN_ODDEVEN ) then
            if ( MOD(SNLC_CID,2) .EQ. 1 ) RETURN
         endif
      endif

c - - - - - - - - - - -
      NCALL_SNANA_DRIVER  = NCALL_SNANA_DRIVER  + 1

c one-time init after first event is read.

      IF ( NCALL_SNANA_DRIVER .EQ. 1 )  THEN

        CALL MON_SNANA(IFLAG_INI)     ! book 1d distributions

        CALL FITPAR_INI2(IERR)


        CALL USRINI2(IERR)        ! generic user function (Dec 2012)

          if ( IERR .NE. 0 ) then
            c1err = 'Problem with 2nd init when NCALL_SNANA_DRIVER=1'
            c2err = 'CID = ' // SNLC_CCID
            CALL  MADABORT(FNAM, C1ERR, C2ERR )
          endif
      ENDIF


c check for SN-dependent filter response
      CALL FILTER_UPDATE_DRIVER()

c compute quantities, apply AB offsets, set cut-mask
      CALL SNRECON()       ! compute variables, apply AB offsets

      CALL U3BAND()        ! special U-band test

      CALL SET_CUTMASK()   ! set cutmask

c check option to include IDEAL fit, after SNRECON (Aug 29 2017)
      CALL SIMFIT_IDEAL_PREP(0)

c set default to use minimized fitpar unless user calls MARG_DRIVER
      USEPDF_MARG = .FALSE.

c check dump-option for SN that fail cuts.

      IF ( .not. LSNCUTS ) THEN
         if ( STDOUT_UPDATE ) write(6,41) SNLC_CCID
41       format(T20,'SNANA cuts REJECT CID = ',A8, 2x,'=> SKIP ')
	 CALL FLUSH(6)
         IF ( LDMP_SNFAIL ) CALL DMP_SNFAIL()
         CALL MON_SNANA(IFLAG_ANA)       ! update ntuples for rejected SN
         RETURN  ! skip this SN
      ENDIF

      IF ( STDOUT_UPDATE ) THEN
        write(6,42) isn_proc
     &        , SNLC_CCID
     &        , ISNLC_NEWMJD_STORE
     &        , ISNLC_NEWMJD_CUTS
      ENDIF

      CALL EXEC_REFORMAT()


c do the fit

       NPLOT_CONT    = 0   ! rest number of contour plots
       ITER          = 0
       LREPEAT_ITER  = .FALSE.
       LREPEAT_MINOS = .FALSE.
       REJECT_FIT    = .FALSE.
       NCALL_MNFIT   = 0

       N_SNLC_FIT = N_SNLC_FIT + 1

       DO 410 WHILE( iter < NFIT_ITERATION .and. .NOT.REJECT_FIT)

          ITER = ITER + 1
          LAST_ITER = ( ITER .EQ. NFIT_ITERATION )

          IF ( ITER==1 ) THEN
              USE_MINOS_LOCAL = .FALSE.
          ELSE
              USE_MINOS_LOCAL = (USE_MINOS .or. LREPEAT_MINOS)
          ENDIF

          CALL FITPAR_PREP ( iter, IERR )  ! init fit params
          if ( IERR .NE. 0 ) then
            ERRFLAG_FIT = IERR
            write(6,40) ITER, SNLC_CCID(1:ISNLC_LENCCID)
40          format(T5,'FITPAR_PREP PROBLEM => SKIP FIT-ITER=',
     &              I2,'  for  CID=',A )
            GOTO 410          ! bad init => skip fit-iteration
          endif

          if ( STDOUT_UPDATE ) THEN
            WRITE(GLOBAL_BANNER,44) ISN_PROC,
     &         SNLC_CCID(1:ISNLC_LENCCID), NFITPAR_MN, ITER
            CALL PRBANNER(GLOBAL_BANNER)
44          format(T5,'CALL MNFIT_DRIVER for ISN_PROC=',I5,
     &           3x,'CID=',A, 3x, 'NFITPAR=',I3, 3x,'iter=',I1 )
          endif

c call main driver for fitter.
c Note that all returned output from MNFIT_DRIVER goes to common blocks.

          CALL MNFIT_DRIVER (
     &       SNLC_CID, NFITPAR_MN                 ! (I)
     &      ,INIVAL, INISTP, INIBND               ! (I)
     &      ,PARNAME_STORE                        ! (I)
     &      ,USE_MINOS_LOCAL                      ! (I)
     &      ,MINUIT_PRINT_LEVEL                   ! (I)
     &      ,FITVAL(1,iter)                       ! (O)
     &      ,FITERR_PLUS(1,iter)                  ! (O)
     &      ,FITERR_MINUS(1,iter)                 ! (O)
     &      ,FITCHI2_MIN                          ! (O)
     &      ,NFIXPAR, ERRTYPE                     ! (O)
     &      ,MNSTAT_COV                           ! (O)
     &      ,IERR                                 ! (O)
     &            )

c avoid infinite loop with MNFIT calls ...
         NCALL_MNFIT = NCALL_MNFIT + 1
         IF  ( NCALL_MNFIT .GT. 2*MXITER ) THEN
            write(c1err,641) 2*MXITER, SNLC_CCID
            write(c2err,642) NFIT_ITERATION
641         format('MNFIT_DRIVER called > ',I3,' times for CID=',A)
642         format('even though NFIT_ITERATION = ', I2 )
            CALL  MADABORT(FNAM, C1ERR, C2ERR )
         ENDIF

c  store fit results

         CALL MNFIT_STOREPAR(iter,IERR)

c analyze results: returns ERRFLAG_FIT
c  =  0 => OK; keep SN
c  >  0 => discard fit
c  = -1 => decrement ITER and try again (e.g., for photoZ spike)

          CALL FITPAR_ANA ( isn_proc, iter, ERRFLAG_FIT )

c check ERRFLAG_FIT
          CALL SNANA_ERRFLAG_FIT(iter,ERRFLAG_FIT)
          if ( ERRFLAG_FIT > 0 ) REJECT_FIT = .TRUE.

410     CONTINUE  ! end of iteration loop

        if ( STDOUT_UPDATE ) THEN
          print*,'    Finished fitting CID = ',
     &         SNLC_CCID(1:ISNLC_LENCCID)
          CALL PRINT_CPU_REMAIN(ISN_ALL)     ! Apr 4 2024
          call flush(6)
        endif



42    format(T8,'Analyze ISN_PROC=',I8, 2x,
     &    'for ',A14,'  NMJD(stored,cuts)=', I4, '->', I4 )
      CALL FLUSH(6)
      CALL USRANA(IERR)     ! call user-analysis routine



      IF ( OPT_TABLE(ITABLE_SPECPAK) > 0  ) THEN
        CALL SPECPLOT()       ! prepare spectra for plotting (Apr 2019)
      ENDIF


c Beware that SNANA table gets filled after FITRES table.
      CALL MON_SNANA(IFLAG_ANA)     ! monitor-driver

      CALL MAKE_SIMLIB_FILE(2)   ! update SIMLIB Feb 2016


      RETURN
      END         ! end of SNANA_DRIVER

C =====================================================
CDECK  ID>,  SNANA_ERRFLAG. 
      SUBROUTINE SNANA_ERRFLAG_FIT(ITER,ERRFLAG)

c Created May 24 2018
c Minor refactor: move some code out of SNANA_DRIVER for cleanup.

      IMPLICIT NONE

      INTEGER ITER, ERRFLAG ! (I)

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNCONTCM. inserted below by ypatchy. 

      INTEGER  MXPLOT_CONT, MXBIN_CONT
      PARAMETER (
     &   MXPLOT_CONT  = 5    ! max number of contour plots per SN
     &  ,MXBIN_CONT   = 100  ! max number of contour bins
     &     )

c define arrays to hold MNCONT informatino for contour plots

      INTEGER
     &   NPLOT_CONT                 ! number of user-contour plots
     &  ,HID_CONT(2,MXPLOT_CONT)    ! store hbook ids for vectors
     &  ,IPAR_CONT(2,MXPLOT_CONT)   ! stores which IPAR for contours
     &  ,NPT_CONT(MXPLOT_CONT)      ! stores Npt per contour plot
     &  ,NPT_FOUND(MXPLOT_CONT)

      REAL*8
     &   VCONT8(MXBIN_CONT,2,MXPLOT_CONT)  ! vector array for IPAR1

      COMMON / CONTOURCOM4 / NPLOT_CONT
     &   ,HID_CONT, IPAR_CONT, NPT_CONT, NPT_FOUND

      COMMON / CONTOURCOM8 /  VCONT8



      LOGICAL LAST_ITER, ALREADY_MINOS

C ------------ BEGIN ----------

      LAST_ITER = ( ITER .EQ. NFIT_ITERATION )

      if ( LAST_ITER ) then
         if ( ERRFLAG == 0 ) then
            N_SNLC_FITCUTS = N_SNLC_FITCUTS + 1
            CUTFLAG_SNANA  = IBSET(CUTFLAG_SNANA,1) ! for SNANA ntuple
            NPASSCUT_FIT(ISNLC_TYPE) = NPASSCUT_FIT(ISNLC_TYPE)+1
            NPASSCUT_FIT(-1)         = NPASSCUT_FIT(-1)+1 ! all types
         endif

c check option to redo entire fit with MINUIT's MINOS option;
c this is a better fit, particularly for errors, but it is
c much slower. So use this only when a serious fit problem is found.
         ALREADY_MINOS = LREPEAT_MINOS .or. USE_MINOS
         if ( ERRFLAG .EQ. -2 .and. (.NOT. ALREADY_MINOS) ) then
            ITER = 0
            LREPEAT_MINOS = .TRUE.
         endif

      endif

c Aug 16, 2009 : check for 1st-iteration cuts,
c such as from filter dropouts  in photoZ fit.

      if ( .NOT.LAST_ITER .and.  ERRFLAG .GT. 0) then
         if ( STDOUT_UPDATE ) write(6,441) SNLC_CCID
 441     format(T4,'MNFIT_DRIVER: ',
     &        'CUTS AFTER 1st FIT-ITER REJECT CID ', A8,' => SKIP')
         CALL MON_SNANA(IFLAG_ANA) ! update ntuples for failed fit
         RETURN
      endif

c check option to redo fit-iteration
      if ( ERRFLAG .EQ. -1 ) then
         ITER         = ITER - 1
         LREPEAT_ITER = .TRUE.
      else
         LREPEAT_ITER = .FALSE.
      endif

      RETURN
      END   ! end SNANA_ERRFLAG_FIT

C ======================================
CDECK  ID>,  SNEND. 
      SUBROUTINE SNANA_END

c Created MAy 2012 by R.Kessler
c
c Shell to call functions after all SN have been processed.
c
c Nov 10 2018: move call to PRINT_SNSTATS() to end of SNANA_END
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


      INTEGER IERR, LENF
      EXTERNAL write_epoch_list_summary

c ----------------- BEGIN -------------

c -----------------------------

      CALL PRBANNER ( "CALL FITPAR_END" )
      CALL FITPAR_END(IERR)


      CALL PRBANNER ( "CALL USREND" )
      CALL USREND ( IERR )

c close hbook file using wrapper so that we don't need CERNLIB flag here.
      IF ( USE_TABLEFILE_HBOOK ) THEN
         LENF = index(HFILE_OUT,' ') - 1
         CALL TABLEFILE_CLOSE(HFILE_OUT(1:LENF)//char(0), LENF)
      ENDIF
      IF ( USE_TABLEFILE_ROOT ) THEN
         LENF = index(ROOTFILE_OUT,' ') - 1
         CALL TABLEFILE_CLOSE(ROOTFILE_OUT(1:LENF)//char(0), LENF)
      ENDIF

      IF ( USE_TABLEFILE_TEXT ) THEN  ! April 2019

c Apr 18 2022: if no events were processed then there are no text files.
c      In this case, create blank text-table file for each table
         IF ( N_SNLC_PROC == 0 ) CALL SNTABLE_CREATE_TEXT_EMPTY()
         CALL TABLEFILE_CLOSE("NULL"//char(0),10)
      ENDIF

      IF ( USE_TABLEFILE_MARZ ) THEN  ! April 2019
         LENF = index(MARZFILE_OUT,' ') - 1
         CALL TABLEFILE_CLOSE(MARZFILE_OUT(1:LENF)//char(0), LENF)
      ENDIF

      IF ( FLAG_NEARNBR == NNFLAG_TRAIN ) THEN
         CALL SNANA_NEARNBR_TRAIN_END()
      ELSE IF ( FLAG_NEARNBR == NNFLAG_APPLY ) THEN
         CALL SNANA_NEARNBR_APPLY_END()
      ENDIF

      CALL MAKE_SIMLIB_FILE(3)  ! end optional SIMLIB FILE

      CALL WARN_OLDINPUTS("list"//char(0), 0);

      CALL END_MAGCOR()  ! check for warnings

c - - - - - -
      CALL PRINT_SNSTATS()

      IF ( OUT_EPOCH_IGNORE_FILE .NE. '' ) then
         CALL write_epoch_list_summary()
      ENDIF

      IF ( REFORMAT_SNANA )  THEN
         CALL END_REFORMAT()
      ENDIF

      call flush(6)
      print*,' '
      print*,'   ENDING PROGRAM GRACEFULLY. '

      RETURN
      END    ! end of SNANA_END


C ======================================
CDECK  ID>,  SNTABLE_CREATE_EMPTY. 
      SUBROUTINE SNTABLE_CREATE_TEXT_EMPTY()
c
c Created Apr 18 2022 by R.Kessler
c Goofy routine called at end of job if no events have been read;
c create empty TEXT table so that submit_batch_jobs finds all of
c the expected TEXT-table files. The underlying problem is that
c TEXT table file is not created until after 1st event is read ...
c so if there is no 1st event then there is no text table file.
c For ROOT and HBOOK, the file is created regardless of 1st event
c because these table formats hold multiple tables in one file.
c --------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      INTEGER NTABLE_CHECK
      PARAMETER (NTABLE_CHECK = 2)
      INTEGER
     &   ITABLE_LIST(NTABLE_CHECK)
     &  ,IDTABLE_LIST(NTABLE_CHECK)
     &  ,itab, ITABLE, IDTABLE, LENNAM, LENFMT
      CHARACTER
     &    TBNAME_LIST(NTABLE_CHECK)*40
     &   ,TBNAME*40, TXTFMT*20
     &   ,cTBNAME*40, cTXTFMT*20

      EXTERNAL SNTABLE_CREATE_TEXT

c --------- BEGIN ----------

      write(6,20)
20    format(/,T3,'No events read -> create empty text-table file:')
      call flush(6)

c hard-wire list of table info to check

      ITABLE_LIST(1)  = ITABLE_SNANA
      ITABLE_LIST(2)  = ITABLE_FITRES

      IDTABLE_LIST(1) = IDTABLE_SNANA
      IDTABLE_LIST(2) = IDTABLE_FITRES

      TBNAME_LIST(1)  = 'SNANA'
      TBNAME_LIST(2)  = 'FITRES'

c - - - - - -
      DO 100 itab =1, NTABLE_CHECK
        ITABLE  = ITABLE_LIST(itab)
        IDTABLE = IDTABLE_LIST(itab)
        TBNAME  = TBNAME_LIST(itab)
        TXTFMT  = 'key'

        IF ( OPT_TABLE(ITABLE) > 0 ) THEN
          LENNAM  = INDEX(TBNAME,' ') - 1
          LENFMT  = INDEX(TXTFMT,' ') -1
          cTBNAME = TBNAME(1:LENNAM) // char(0)
          cTXTFMT = TXTFMT(1:LENFMT) // char(0)
          CALL SNTABLE_CREATE_TEXT(IDTABLE, cTBNAME, cTXTFMT, 40,20)
        ENDIF
100   CONTINUE

      RETURN
      END

C ======================================
CDECK  ID>,  FORCLOSE. 
      SUBROUTINE FORCLOSE(LUN)
c Apr 2014:
c Wrapper to close a fortran logical unit from C code;
c needed by CLOSE_HFILE in sntools_output_hbook.c
      INTEGER LUN
      CLOSE(LUN)
      RETURN
      END

C ===========================================
CDECK  ID>,  REJECTPS. 
      LOGICAL FUNCTION  REJECT_PRESCALE(N,PRESCALE)

c Created Jan 2015
c Apply &SNLCINP SIM_PRESCALE (if >1) to randomly pre-scale
c the simulation. Use reproducible random numbers based
c on input integer N (incremental index) ,
c   RAN = mod(N,PI)/PI
c
c Apr 26 2017: pass PRESCALE as argument.

      IMPLICIT NONE

      INTEGER N           ! (I) use for pseudo-random pre-scale
      REAL*8  PRESCALE    ! (I) prescale
c local var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


c +CDE,SNDATCOM.
c +CDE,SNLCINP.

      DOUBLE PRECISION XN, RAN, RANMAX

C ------------- BEGIN --------------

      REJECT_PRESCALE = .FALSE.

      IF ( PRESCALE < 1.000001 ) RETURN

      XN     = DBLE(N)
      RAN    = mod(XN,PI)/PI
      RANMAX = 1.0/PRESCALE
      IF ( RAN > RANMAX ) REJECT_PRESCALE = .TRUE.

      RETURN
      END

C =============================
CDECK  ID>,  INIT_REFORMAT. 
      SUBROUTINE INIT_REFORMAT(OPT)
c
c Create Feb 7 2021;
c Initialize option to reformat data
c Input OPT=1 -> Auto-set bits
c Input OPT=2 -> call INIT_REFORMAT_[FITS,TEXT,SPECTRA]
c
c Note that REFORMAT_FITS[TEXT] operates on all of the data: header, photometry,spectra;
c however, REFORMAT_SPECTRA operates only on the spectra and ignores header & photometry
c
c OPT_REFORMAT_FITS[TEXT] bits:
c  lsb   mask  comment
c   0     1    write fits;
c   1     2    include rejected epochs
c   2     4     SPARE
c   3     8     SPARE
c   4    16     SPARE
c   5    32     SPARE
c   6    64    exclude private variables
c   7   128    include spectra
c   8   256    exclude SIM-truth so that output looks like real data
c   9   512     SPARE
c
c
c OPT_REFORMAT_SPECTRA bits:
c  lsb  mask
c   0    1      3-column text format: lam, Flam, Flam_err
c   1    2      3-column text format: lam, Flux, Flux_err
c
c ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c
c       HISTORY
c July 2023: check OPT_REFORMAT_SPECTRA
c
c -------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER OPT

      INTEGER LEN_VER
      LOGICAL LEXIST, VALIDFILENAME
      CHARACTER
     &   FNAM*14
     &  ,LIST_FILE*(MXCHAR_FILENAME), IGNORE_FILE*(MXCHAR_FILENAME)
     &  ,CMD*(MXCHAR_FILENAME)
C ------------- BEGIN -------------

      FNAM = 'INIT_REFORMAT'

      IF ( OPT == 2 ) GOTO 500

      REFORMAT       = .FALSE.  ! any reformat option
c - - - - - - - - -
c convert &SNLCINP strings and OPT_REFORMAT_TEXT[FITS] into logicals

      IF ( VALIDFILENAME(VERSION_REFORMAT_FITS) ) THEN
        OPT_REFORMAT_FITS = IBSET(OPT_REFORMAT_FITS,0) ! set 1st bit
      ENDIF
      IF ( VALIDFILENAME(VERSION_REFORMAT_TEXT) ) THEN
        OPT_REFORMAT_TEXT = IBSET(OPT_REFORMAT_TEXT,0) ! set 1st bit
      ENDIF

c check option to save bad epochs for OPT_REFORMAT
      IF ( BTEST(OPT_REFORMAT_FITS,1) .or.
     &     BTEST(OPT_REFORMAT_TEXT,1) ) THEN
         REFORMAT_SAVE_BADEPOCHS = .TRUE.
      ENDIF

c check option to suppress PRIVATE variables: MASK+=64 or bit 6 (lsb=0)
      IF ( BTEST(OPT_REFORMAT_FITS,6) .or.
     &     BTEST(OPT_REFORMAT_TEXT,6) ) THEN
         REFORMAT_PRIVATE = .FALSE.
      ENDIF

c check option to reformat spectra: note that for TEXT -> FITS,
c spectra may not appear in 1st text file, so user must explicitly
c request reformatting spectra. MASK=128 -> bit 7
c
      IF ( BTEST(OPT_REFORMAT_FITS,7) .or.
     &     BTEST(OPT_REFORMAT_TEXT,7) ) THEN
         REFORMAT_SPECTRA_INCLUDE = .TRUE.
      ENDIF

c check option to exclude SIM truth; MASK += 256
      IF ( BTEST(OPT_REFORMAT_FITS,8) .or.
     &     BTEST(OPT_REFORMAT_TEXT,8) ) THEN
         REFORMAT_SIMTRUTH = .FALSE.
      ENDIF

c - - - - - - - - - - - - - - - - - -
c check for reformat option using SNANA format

      REFORMAT_SNANA = (OPT_REFORMAT_FITS>0 .or. OPT_REFORMAT_TEXT>0)

      IF ( REFORMAT_SNANA ) THEN

         IF ( OPT_REFORMAT_FITS > 0 ) THEN
            REFORMAT_VERSION = VERSION_REFORMAT_FITS
         ELSE IF ( OPT_REFORMAT_TEXT > 0 ) THEN
            REFORMAT_VERSION = VERSION_REFORMAT_TEXT
         ENDIF

c check if reformat dir already exists
         LEN_VER = INDEX(REFORMAT_VERSION,' ')-1
         INQUIRE(FILE = REFORMAT_VERSION, EXIST = LEXIST)
         IF ( LEXIST ) THEN
            c1err = 'REFORMAT DIR already exists: '
     &           // REFORMAT_VERSION(1:LEN_VER)
            c2err = 'Remove it, or change name'
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         ENDIF

         ! create reformat directory
         CMD = 'mkdir ' // REFORMAT_VERSION(1:LEN_VER)
         CALL SYSTEM(CMD)

c open aux files and leave them open
         CALL OPEN_REFORMAT_FILE(LUNLIST2,   'LIST',   LIST_FILE)

         CALL OPEN_REFORMAT_FILE(LUNIGNORE2, 'IGNORE', IGNORE_FILE)
         write(LUNIGNORE2,420)     ! write header
 420     format(T10,'CID      MJD     FILTER')
         NEPOCH_IGNORE_WRFITS = 0
      ENDIF

      REFORMAT = OPT_REFORMAT_FITS>0 .or. OPT_REFORMAT_TEXT>0
     &      .or. OPT_REFORMAT_SALT2>0

      REFORMAT_SPECTRA_ONLY = (OPT_REFORMAT_SPECTRA > 0 )

c - - - - -
c print info

      IF ( REFORMAT ) THEN
         print*,' '
         print*,'   INIT_REFORMAT options: '
         print*,'     OPT_REFORMAT_[FITS,TEXT] = ',
     &              OPT_REFORMAT_FITS, OPT_REFORMAT_TEXT
         print*,'     REFORMAT_BADEPOCHS       = ',
     &                 REFORMAT_SAVE_BADEPOCHS
         print*,'     REFORMAT_SPECTRA_INCLUDE = ',
     &                REFORMAT_SPECTRA_INCLUDE
         print*,'     REFORMAT_PRIVATE         = ',
     &                REFORMAT_PRIVATE
         print*,'     REFORMAT_SIMTRUTH        = ',
     &                REFORMAT_SIMTRUTH
      ENDIF

      IF ( REFORMAT_SPECTRA_ONLY ) THEN
         print*,' '
         print*,'   INIT_REFORMAT options: '
         print*,'     OPT_REFORMAT_SPECTRA  = ', OPT_REFORMAT_SPECTRA
      ENDIF

         call flush(6)

      RETURN
c - - - - - - - - - -

500   CONTINUE

      IF ( OPT_REFORMAT_FITS  >  0 ) THEN
         CALL INIT_REFORMAT_FITS()
      ENDIF

      IF ( OPT_REFORMAT_TEXT  > 0 ) THEN
         CALL INIT_REFORMAT_TEXT()
      ENDIF

      IF ( OPT_REFORMAT_SALT2 .EQ. 2 ) THEN
         CALL INIT_REFORMAT_SALT2()
      ENDIF

      IF ( OPT_REFORMAT_SPECTRA > 0 ) THEN
         CALL INIT_REFORMAT_SPECTRA_ONLY()
      ENDIF

      RETURN
      END     ! end INIT_REFORMAT

C ============================================
CDECK  ID>,  INIT_REFORMAT_FITS. 
      SUBROUTINE INIT_REFORMAT_FITS

c Prepare for translating text file format into FITS format.
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      CHARACTER
     &   cPATH*(MXCHAR_PATH)
     &  ,cVERSION*(MXCHAR_VERSION)
     &  ,cPREFIX*(MXCHAR_VERSION)
     &  ,cHEADFILE*(MXCHAR_FILENAME)
     &  ,LIST_FILE*(MXCHAR_FILENAME)
     &  ,IGNORE_FILE*(MXCHAR_FILENAME)

      INTEGER
     &   WRITE_FLAG, LL, NMARK
     &  ,LEN_DIR
     &  ,LEN_SURVEY
     &  ,LEN_VERS
     &  ,LEN_HEAD

C ------------------ BEGIN ----------------

      LEN_SURVEY = INDEX(SURVEY_NAME,' ') - 1

      LEN_VERS = INDEX(VERSION_REFORMAT_FITS,' ') - 1
      cVERSION = VERSION_REFORMAT_FITS(1:LEN_VERS) // char(0)
      cPREFIX  = cVERSION

      LEN_DIR    = INDEX(REFORMAT_VERSION,' ') - 1
      cPATH      = REFORMAT_VERSION(1:LEN_DIR) // char(0)

c to see flags in C code, "grep WRITE_MASK sndata.h"
      IF ( LSIM_MAGOBS ) THEN
         WRITE_FLAG = 8   ! Jan 23 2018
      ELSE IF ( LSIM_SNANA ) THEN
         WRITE_FLAG = 4   ! Jan 23 2018
         if ( .NOT. REFORMAT_SIMTRUTH ) WRITE_FLAG = 2 ! Mar 2022
      ELSE
         WRITE_FLAG = 2
      ENDIF

      if ( REFORMAT_SPECTRA_INCLUDE ) WRITE_FLAG = WRITE_FLAG + 128
      if ( FOUND_ATMOS              ) WRITE_FLAG = WRITE_FLAG + 256

c -----------------------
      CALL WR_SNFITSIO_INIT(cPATH, cVERSION, cPREFIX, WRITE_FLAG
     &           , NMARK, cHEADFILE  ! output name
     &           , LEN_DIR, LEN_VERS, LEN_VERS, LEN_HEAD)

c --- write name of HEAD file to already-opend LIST file

      LL = INDEX(cHEADFILE, char(0) ) - 1
      WRITE(LUNLIST2,50) cHEADFILE(1:LL)
50    FORMAT(A)
      CLOSE(LUNLIST2)

      RETURN
      END  ! end  INIT_REFORMAT_FITS

C ===============================
CDECK  ID>,  INIT_REFORMAT_TEXT. 
      SUBROUTINE INIT_REFORMAT_TEXT()
      IMPLICIT NONE
cc      print*,'  INI_WRTEXT: placeholder -> do nothing ... yet'
      RETURN
      END

C ====================================
CDECK  ID>,  INIT_REFORMAT_SALT2. 
      SUBROUTINE INIT_REFORMAT_SALT2
c -----------------------------------------------
c Nov 2011 R.Kessler
c
c Initialization for translating SNANA formatted data
c into SALT2-formatted data. The input options are fed
c vis &SNLCINP namelist string
c
c  &SNLCINP
c     ...
c   REFORMAT_KEYS =
c   '@INSTRUMENT <instr> @MAGSYS <magsys> @PREFIX <prefix> @REPLACE <f1> <f2>
c     ...
c  &END
c
c where @INSTRUMENT and @MAGSYS are required and the others are optional.
c Definition of above keys
c
c @INSTRUMENT = name of telescope or survey defined by SALT2
c @MAGSYS     = mag system defined by SALT2 (i.e, AB, VEGA ...)
c @PREFIX     = file-name prefix (default prefix is name of survey)
c @REPLACE    = replace filter list <f1> with <f2>. For example,
c               if f1 = UGRIZ and f2 = ugriz, then U -> u, G -> g,
c               etc in the output SALT2 files.
c
c
c ------------------------------
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,WRS2COM. inserted below by ypatchy. 

c Nov 03, 2011:
c common block for translating SNANA format into SALT2 format.

      INTEGER
     &   LEN_SURVEY, LEN_INST, LEN_MAGSYS,  LEN_PREFIX
     &  ,NREPLACE, IMAP_REPLACE(MXFILT_ALL)
     &  ,NEWKEY

      CHARACTER
     &   NAMEof_INSTRUMENT*(MXCHAR_FILEWORD)
     &  ,NAMEof_MAGSYS*(MXCHAR_FILEWORD)
     &  ,NAMEof_SURVEY*(MXCHAR_FILEWORD)
     &  ,NAMEof_PREFIX*(MXCHAR_FILEWORD)
     &  ,NAMEof_REPLACE(2)*(MXCHAR_FILEWORD)
     &  ,NEWKEY_NAME(20)*(MXCHAR_FILEWORD)
     &  ,NEWKEY_ARG(20)*(MXCHAR_FILEWORD)

      COMMON / WRS2COM /
     &   LEN_SURVEY, LEN_INST, LEN_MAGSYS, LEN_PREFIX
     &  ,NREPLACE, IMAP_REPLACE, NEWKEY
     &  ,NAMEof_INSTRUMENT, NAMEof_MAGSYS
     &  ,NAMEof_SURVEY, NAMEof_PREFIX
     &  ,NAMEof_REPLACE, NEWKEY_NAME, NEWKEY_ARG

C =================================================

      INTEGER iwd, NWD, ifilt, NTMP, IFILT_OBS, IFILT_TMP(2)
      INTEGER LL, LL0, LL1, LL2, MSKOPT
      character
     &   cwd*(MXCHAR_FILEWORD-2)
     &  ,cwd1*(MXCHAR_FILEWORD-2)
     &  ,cwd2*(MXCHAR_FILEWORD-2)
     &  ,ctmp*(MXCHAR_FILEWORD-2)
     &  ,cfilt(2)*2, cfilt1*1
     &  ,cutvar_file*(MXCHAR_FILENAME)
     &  ,list_file*(MXCHAR_FILENAME)
     &  ,FNAM*30

c function
      INTEGER FILTINDX

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS
C -------------------- BEGIN -------------------

      FNAM = 'INIT_REFORMAT_SALT2'
      CALL PRBANNER("INI_WRSALT2: Translate SNANA -> SALT2 format")

      LL = INDEX(REFORMAT_KEYS,' ') -1
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      NWD = STORE_PARSE_WORDS(MSKOPT, REFORMAT_KEYS(1:LL)//char(0),
     &         FNAM//char(0), LL, 30)

      NAMEof_SURVEY        = 'NULL'
      NAMEof_INSTRUMENT    = 'NULL'
      NAMEof_MAGSYS        = 'NULL'
      NAMEof_PREFIX        =  SURVEY_NAME
      NAMEof_REPLACE(1)    = 'NULL'
      NAMEof_REPLACE(2)    = 'NULL'

      NREPLACE = 0
      NEWKEY = 0

      DO ifilt = 1, MXFILT_ALL
           IMAP_REPLACE(IFILT) = -9
      ENDDO

      DO iwd = 1, NWD

        CALL get_PARSE_WORD_fortran(iwd+0, cwd,  LL0 )
        CALL get_PARSE_WORD_fortran(iwd+1, cwd1, LL1 )

        if ( cwd(1:LL0) .EQ. '@SURVEY' ) then
          NAMEof_SURVEY = cwd1

        else if ( cwd(1:LL0) .EQ. '@INSTRUMENT' ) then
          NAMEof_INSTRUMENT = cwd1

        else if ( cwd(1:LL0) .EQ. '@MAGSYS' ) then
          NAMEof_MAGSYS = cwd1

        else if ( cwd(1:LL0) .EQ. '@PREFIX' ) then
          NAMEof_PREFIX = cwd1

        else if ( cwd(1:LL0) .EQ. '@REPLACE' ) then
           CALL get_PARSE_WORD_fortran(iwd+2, cwd2, LL2 )
          NAMEof_REPLACE(1) = cwd1
          NAMEof_REPLACE(2) = cwd2
          NREPLACE    = INDEX(NAMEof_REPLACE(1), ' ' ) - 1
        else if ( cwd(1:1) .EQ. '@' ) then
          NEWKEY = NEWKEY + 1
          NEWKEY_NAME(NEWKEY)(1:LL0-1) = cwd(2:LL0)
          NEWKEY_ARG(NEWKEY)           = cwd1
        endif

      ENDDO

      LEN_SURVEY  = INDEX(NAMEof_SURVEY,    ' ' ) - 1
      LEN_INST    = INDEX(NAMEof_INSTRUMENT,' ' ) - 1
      LEN_MAGSYS  = INDEX(NAMEof_MAGSYS,    ' ' ) - 1
      LEN_PREFIX  = INDEX(NAMEof_PREFIX,    ' ' ) - 1

c make sure that required keys are specified.

      if ( NAMEof_INSTRUMENT .EQ. 'NULL' ) then
        c1err = 'MUST specify @INSTRUMENT <instrument> in '
        c2err = '&SNLCINP namelist string REFORMAT_KEYS'
        CALL  MADABORT("WRSALT2_2", C1ERR, C2ERR)
      endif
      if ( NAMEof_MAGSYS .EQ. 'NULL' ) then
        c1err = 'MUST specify @MAGSYS <magsys> in '
        c2err = '&SNLCINP namelist string REFORMAT_KEYS'
        CALL  MADABORT("WRSALT2_2", C1ERR, C2ERR)
      endif

c ----------
c Check for filter-name substitutions;
c i.e., UGRIZ -> ugriz for the SDSS

      IF ( NREPLACE .GT. 0  ) THEN

c abort if filter-strings have different length
        NTMP   = INDEX(NAMEof_REPLACE(2), ' ' ) - 1
        IF ( NREPLACE .NE. NTMP ) THEN
          c1err = 'Filter @REPALCE strings have different length'
          c2err = 'Cannot replace ' //
     &              NAMEof_REPLACE(1)(1:NREPLACE) // ' with ' //
     &              NAMEof_REPLACE(2)(1:NTMP)
          CALL  MADABORT("WRSALT2_2", C1ERR, C2ERR)
        ENDIF

c create map between original filter and subst. filter

        DO 55 ifilt = 1, NREPLACE
           cfilt(1) = NAMEof_REPLACE(1)(ifilt:ifilt)
           cfilt(2) = NAMEof_REPLACE(2)(ifilt:ifilt)
           IFILT_TMP(1) = FILTINDX ( cfilt(1) )
           IFILT_TMP(2) = FILTINDX ( cfilt(2) )
           IMAP_REPLACE(IFILT_TMP(1)) = IFILT_TMP(2)

           write(6,56) cfilt, IFILT_TMP
56         format(t10,'Prepare @REPLACE map for ' , A2,' -> ', A2,
     &       '(', I2,' -> ', I2, ')' )

55      CONTINUE
      ENDIF

c ----------------------------
c  open list-file and leave it open.

      LIST_FILE = NAMEof_PREFIX(1:LEN_PREFIX) // '.LIST'
      print*,'   Open list-file: ', LIST_FILE(1:LEN_PREFIX+12)

      OPEN( UNIT   = LUNSALT2
     &    , FILE   = LIST_FILE
     &    , STATUS = 'UNKNOWN'
     &           )

c ----------------------------
c write cut-def file, then close it.

      CUTVAR_FILE = NAMEof_PREFIX(1:LEN_PREFIX) // '_CUTVAR.LOG'
      print*,'   Write cut-definitions to ' //
     &    CUTVAR_FILE(1:LEN_PREFIX+12)

      OPEN( UNIT   = LUNTMP
     &    , FILE   = CUTVAR_FILE
     &    , STATUS = 'UNKNOWN'
     &           )

      write(LUNTMP,111) 'Z_HELIO   ',
     &       'heliocentric redshift'
      write(LUNTMP,111) 'MWEBV     ',
     &       'Galactic E(B-V)'
      write(LUNTMP,111) 'MWEBV_ERR     ',
     &       'error on Galactic E(B-V)'

        write(ctmp,401) int(cutwin_trest(1)), int(cutwin_trest(2))
401     format(I3,'<Trest<' , I3,' days')
        write(LUNTMP,111) 'NOBS      ',
     &       'Nobs total with any S/N and ' // ctmp(1:20)
        write(LUNTMP,111) 'TRESTMIN  ',
     &       'min Trest(days) relative to peak (any S/N)'
        write(LUNTMP,111) 'TRESTMAX  ',
     &       'max Trest(days) relative to peak (any S/N)'

        write(LUNTMP,111) 'T0GAPMAX  ',
     &       'max rest-frame gap (days) that overlaps peak epoch'

        write(LUNTMP,111) 'SNRMAX    ',
     &       'max S/N among all observations'
        write(LUNTMP,111) 'SNRMAX2   ',
     &       'max S/N excluding filter with SNRMAX'

        write(LUNTMP,111) 'SNRMAX3   ',
     &       'max S/N excluding filters with SNRMAX & SNRMAX2'


        write(LUNTMP,600) ' '
        DO IFILT     = 1, NFILTDEF_SURVEY
           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
           cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
           ctmp      = 'SNRMAX_' // cfilt1
           LL        = INDEX(ctmp,' ') - 1
           write(LUNTMP,111) ctmp(1:10),
     &       'max S/N for indicated filter'
        ENDDO

      IF ( OPT_SETPKMJD > 0 ) THEN
        write(LUNTMP,600) ' '
        DO IFILT     = 1, NFILTDEF_SURVEY
           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
           cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
           ctmp      = 'ERRT0_' // cfilt1
           LL        = INDEX(ctmp,' ') - 1
           write(LUNTMP,111) ctmp(1:10),
     &       'fitted T0 error (days) for indicated filter'
        ENDDO

        write(LUNTMP,600) ' '
        DO IFILT     = 1, NFILTDEF_SURVEY
           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
           cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
           ctmp      = 'ERRF0_' // cfilt1
           LL        = INDEX(ctmp,' ') - 1
           write(LUNTMP,111) ctmp(1:10),
     &       'ERR(F0)/F0 for indicated filter'
        ENDDO

      ENDIF

111     format('@', A, ' : ', A)
600     format(A)
        CLOSE(UNIT=LUNTMP)

      print*,' -----------------------------------------------'
      print*,' '
      RETURN
      END    ! end INIT_REFORMAT_SALT2

C ====================================
CDECK  ID>,  INIT_REFORMAT_SPECTRA. 
      SUBROUTINE INIT_REFORMAT_SPECTRA_ONLY()

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C --------------- BEGIN ------------

c  For now do nothing (no new folder) and write spec files in cwd.
c  The idea is that organization of folders is done by code calling
c  snana.exe with OPT_REFORMAT_SPECTRA option.
c
c  file name = [version]_snid[snid]-mjd[mjd].spec

      RETURN
      END   ! end INIT_REFORMAT_SPECTRA_ONLY


C ================================================
CDECK  ID>,  OPEN_REFORMAT_FILE. 
      SUBROUTINE OPEN_REFORMAT_FILE(LUN, SUFFIX, REFORMAT_FILE)
c Open text file name REFORMAT_VERSION/REFORMAT_VERSION.SUFFIX
c use imput LUN
      IMPLICIT NONE
      INTEGER   LUN          ! (I) open with this logical unit
      CHARACTER SUFFIX*(*)   ! (I) open with this suffix
      CHARACTER REFORMAT_FILE*(*)  ! (O) name of file opened


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


      INTEGER   LEN_VER

C ------------ BEGIN -----------
      LEN_VER = INDEX(REFORMAT_VERSION,' ') - 1
      REFORMAT_FILE =
     &   REFORMAT_VERSION(1:LEN_VER) // '/' //
     &   REFORMAT_VERSION(1:LEN_VER) // '.' // SUFFIX

      OPEN (LUN, FILE = REFORMAT_FILE, status='UNKNOWN' )

      RETURN
      END      ! OPEN_REFORMAT_FILE

C =============================
CDECK  ID>,  EXEC_REFORMAT. 
      SUBROUTINE EXEC_REFORMAT()
c
c Create Feb 7 2021;
c Update reformat output:
c  + append FITS files for FITS output
c  + write new TEXT file for TEXT output
c
c Jan 20 2022: move copy_SNDATA_MISC() to work for either TEXT for FITS.
c Jul 18 2023: check OPT_REFORMAT_SPECTRA
c -------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER MXWR_TEXT
      PARAMETER (MXWR_TEXT = 400)

      LOGICAL    NOT_TOO_MANY
      CHARACTER  CCID*(MXCHAR_CCID), TEXTFILE*100, TEXTFILE_FULL*100
      INTEGER    LEN_VER, LEN_TXT, LEN_S
      EXTERNAL   WR_SNTEXTIO_DATAFILE

C ---------- BEGIN ----------

      if ( .NOT. ( REFORMAT .or. REFORMAT_SPECTRA_ONLY)  ) RETURN

      IF ( REFORMAT_SNANA ) THEN
         CALL WRITE_REFORMAT_IGNORE()  ! update ignore file
      ENDIF

      CALL copy_SNDATA_MISC() ! update SNDATA structure

      IF ( OPT_REFORMAT_FITS > 0 )  THEN
         CALL WR_SNFITSIO_UPDATE()
      ENDIF

      NOT_TOO_MANY = (N_SNLC_CUTS .LE. MXWR_TEXT)
      IF ( OPT_REFORMAT_TEXT > 0  .and. NOT_TOO_MANY ) THEN
c        prepare name of text file
         CCID    = SNLC_CCID(1:ISNLC_LENCCID)
         LEN_VER = INDEX(REFORMAT_VERSION,' ') - 1
         LEN_S   = INDEX(SURVEY_NAME,' ') - 1
         textFile =
cc xxx     &       REFORMAT_VERSION(1:LEN_VER) // '_' //
     &       SURVEY_NAME(1:LEN_S) // '_' //
     &       SNLC_CCID(1:ISNLC_LENCCID) // '.DAT'
         LEN_TXT = INDEX(textfile,' ') - 1
         TEXTFILE_FULL = REFORMAT_VERSION(1:LEN_VER) // '/'  //
     &       textfile(1:len_txt) // char(0)

         CALL WR_SNTEXTIO_DATAFILE(TEXTFILE_FULL, 100)
         write(LUNLIST2, '(A)' ) TEXTFILE(1:len_txt)

         if ( N_SNLC_CUTS == MXWR_TEXT ) then
            print*,' '
            print*,'  WARNING: wrote max number of TEXT files: ',
     &                N_SNLC_CUTS
            print*,' '
         endif
      ENDIF

c check Julien's original SALT2 format (not SNANA format)
      IF ( OPT_REFORMAT_SALT2 .EQ. 2 ) THEN
         CALL WRSALT2_2()
      ENDIF

      IF ( REFORMAT_SPECTRA_ONLY ) THEN
        CALL WR_SPECTRA()
      ENDIF

      RETURN
      END     ! end EXEC_REFORMAT

C =====================================
CDECK  ID>,  copy_SNDATA_MISC. 
      SUBROUTINE copy_SNDATA_MISC()

c Created Mar 14 2021
c Update the following SNDATA struct variables for FITS or TEXT format:
c   + PEAKMJD                ( if OPT_SETPKMJD > 0)
c   + MWEBV[_ERR]            ( if OPT_MWEBV    > 0)
c   + REDSHIFT_CMB[_ERR]
c   + REDSHIFT_HELIO[_ERR]
c   + VPEC[_ERR]
c   + NPRIVATE               set to 0 OPT_REFORMAT_PRIVATE=F (Jan 2022)
c   + HOSTGAL_LOGMASS[_ERR]  ??? TO DO (how to handle mutliple hosts?)
c   + HOSTGAL_sSFR[_ERR]     ??? TO DO (idem)
c
c   + FLUXCAL      # if MAGCOR_INFILE is set  (Dec 2021)
c   + FLUXCALERR   # if FLUXMODELERR_FILE is set (Dec 2021)
c
c   + MJD_TRIGGER        # if PHOTFLAG_TRIGGER > 0
c   + MJD_DETECT_FIRST   # if PHOTFLAG_DETECT > 0
c   + MJD_DETECT_LAST    # idem
c
c   + MWMAGCOR_[band]  # Nov 2023
c -------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER COPYFLAG, NARG, NOBS, LEN_KEY, LEN_STR, o
      INTEGER IFILT, IFILT_OBS
      REAL*8 DVAL(MXEPOCH)
      CHARACTER cKEY*20, cSTRING*20, cfilt*2
      EXTERNAL COPY_SNDATA_HEAD

C -------------- BEGIN ----------

      NARG     =  1
      NOBS     =  ISNLC_NEWMJD_FOUND
      COPYFLAG = +1
      LEN_KEY  = 20
      LEN_STR  = 20
      cSTRING  = "DUMMY" // char(0)

      IF ( OPT_SETPKMJD > 0 ) THEN
        cKEY     = "PEAKMJD" // char(0)
        DVAL(1)     = DBLE(SNLC_SEARCH_PEAKMJD)
        CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)
      ENDIF

      IF ( OPT_MWEBV > 0 ) THEN
        cKEY     = "MWEBV" // char(0)
        DVAL(1)  = DBLE(SNLC_MWEBV)
        CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

        cKEY     = "MWEBV_ERR" // char(0)
        DVAL(1)  = DBLE(SNLC_MWEBV_ERR)
        CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

c write MWXT mag as diagnostic (not used)
        do ifilt     = 1, NFILTDEF_SURVEY
           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
           cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
           cKEY      = 'MWXT_MAG_' // cfilt(1:1) // char(0)
           DVAL(1)   = SNLC_MWXT_MAG(ifilt)
           CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &           cSTRING, DVAL, LEN_KEY, LEN_STR)
        end do

      ENDIF

c always update redshift and vpec info in case of header-override
c or other calculated update.

c zCMB
      cKEY     = "REDSHIFT_CMB" // char(0)
      DVAL(1)  = DBLE(SNLC_zCMB)
      CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

      cKEY     = "REDSHIFT_CMB_ERR" // char(0)
      DVAL(1)  = DBLE(SNLC_zCMB_ERR)
      CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

c zHELIO
      cKEY     = "REDSHIFT_HELIO" // char(0)
      DVAL(1)  = DBLE(SNLC_zHELIO)
      CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

      cKEY     = "REDSHIFT_HELIO_ERR" // char(0)
      DVAL(1)  = DBLE(SNLC_zHELIO_ERR)
      CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

c VPEC
      cKEY     = "VPEC" // char(0)
      DVAL(1)  = DBLE(SNLC_VPEC)
      CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

      cKEY     = "VPEC_ERR" // char(0)
      DVAL(1)  = DBLE(SNLC_VPEC_ERR)
      CALL copy_SNDATA_HEAD(COPYFLAG, cKEY, NARG,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)

c check option to exclude PRIVATE variables from output.
c Do NOT modify NVAR_PRIVATE.
      IF ( .NOT. REFORMAT_PRIVATE .and. NVAR_PRIVATE > 0 ) then
        cKEY     = "NVAR_PRIVATE"  // char(0)
        DVAL(1)  = -1.0   ! -1 means disable to avoid abort on NVAR change
        CALL copy_SNDATA_GLOBAL(COPYFLAG, cKEY, NARG,
     &          cSTRING, DVAL, LEN_KEY, LEN_STR)
      ENDIF

c ----
c update logmass and sSFR
c ------
      IF ( DOFUDGE_FLUXERRMODEL ) THEN
         cKEY  = "FLUXCALERR" // char(0)
         DO o=1,NOBS; DVAL(o)=SNLC_FLUXCAL_ERRTOT(o) ; END DO
         CALL copy_SNDATA_OBS(copyFlag, cKEY, NOBS,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)
      ENDIF

      IF ( NSTORE_MAGCOR > 0 ) THEN
         cKEY  = "FLUXCAL" // char(0)
         DO o=1,NOBS; DVAL(o)=SNLC_FLUXCAL(o) ; END DO
         CALL copy_SNDATA_OBS(copyFlag, cKEY, NOBS,
     &        cSTRING, DVAL, LEN_KEY, LEN_STR)
      ENDIF

c Sep 2023: update MJD_TRIGGER and MJD_DETECT_XYZ variables
c           if they have been computed from PHOTFLAG .

      if ( PHOTFLAG_TRIGGER > 0 ) then
         cKEY = "MJD_TRIGGER" // char(0)
         DVAL(1) = SNLC8_MJD_TRIGGER
         CALL copy_SNDATA_HEAD(copyFlag, cKEY, NARG,
     &         cSTRING, DVAL, LEN_KEY, LEN_STR)
      endif

      if ( PHOTFLAG_DETECT > 0 ) then
         cKEY = "MJD_DETECT_FIRST" // char(0)
         DVAL(1) = SNLC8_MJD_DETECT_FIRST
         CALL copy_SNDATA_HEAD(copyFlag, cKEY, NARG,
     &         cSTRING, DVAL, LEN_KEY, LEN_STR)

         cKEY = "MJD_DETECT_LAST" // char(0)
         DVAL(1) = SNLC8_MJD_DETECT_LAST
         CALL copy_SNDATA_HEAD(copyFlag, cKEY, NARG,
     &         cSTRING, DVAL, LEN_KEY, LEN_STR)
      endif

      RETURN
      END

C =========================================
CDECK  ID>,  WR_REFORMAT_IGNORE. 
      SUBROUTINE WRITE_REFORMAT_IGNORE()

c Open and write IGNORE file

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


      INTEGER i, LEN1_CCID, LEN2_CCID
      CHARACTER CCID*(MXCHAR_CCID)
C ----------- BEGIN ----------

      LEN1_CCID = INDEX(SNLC_CCID,' ') - 1
      DO 400 i = 1, NEPOCH_IGNORE
         CCID = EPOCH_IGNORE_CCID(i)
         LEN2_CCID = INDEX(CCID,' ') - 1
         IF( LEN1_CCID .NE. LEN2_CCID ) GOTO 400
         IF ( CCID(1:LEN1_CCID) .EQ. SNLC_CCID(1:LEN1_CCID) ) THEN
            write(LUNIGNORE2,410)
     &      CCID(1:LEN1_CCID), EPOCH_IGNORE_MJD(i), EPOCH_IGNORE_FILT(i)
 410        format('IGNORE:  ', A, 3x, F9.3, 3x, A1)
            call flush(LUNIGNORE2)
            NEPOCH_IGNORE_WRFITS = NEPOCH_IGNORE_WRFITS + 1
         ENDIF
 400  CONTINUE

      RETURN
      END  ! end of WRITE_REFORMAT_IGNORE


C ===============================
CDECK  ID>,  WR_SPECTRA. 
      SUBROUTINE WR_SPECTRA()

c Created July 2023
c For each spectrum, re-write using format based on OPT_REFORMAT_SPECTRA.
c File name is
c   [version]-snid[snid]-mjd[mjd].spec
c
c Iniitial code writes only one format, but later this could be expanded
c to write different formats.
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


      INTEGER LENV, LENC, ispec, NLAMBIN, ilam
      REAL*8  MJD, LAM, LAMBIN, F, FERR
      CHARACTER SPEC_FILE*(MXCHAR_FILENAME), MSG*80
      LOGICAL WR_FLAM, WR_FLUX
C ------------- BEGIN -----------

      LENV = INDEX(VERSION_PHOTOMETRY(1),' ') - 1
      LENC = ISNLC_LENCCID

      WR_FLAM = BTEST(OPT_REFORMAT_SPECTRA,0)
      WR_FLUX = BTEST(OPT_REFORMAT_SPECTRA,1)

      DO 400 ispec = 1, NSPECTRUM

         CALL RDSPEC_DRIVER(ispec)  ! load LAM and FLAM arrays

         MJD     = MJD_SPECTRUM(ispec)
         NLAMBIN = NLAMBIN_SPECTRUM(ispec)

         if ( MJD > 0.0 ) THEN
             WRITE(SPEC_FILE,40)
     &       VERSION_PHOTOMETRY(1)(1:LENV), SNLC_CCID(1:LENC), MJD
40          format(A,'_',A,'_', F9.3, '.SPEC' )
         ELSE
             WRITE(SPEC_FILE,41)
     &       VERSION_PHOTOMETRY(1)(1:LENV), SNLC_CCID(1:LENC), "HOST"
41          format(A,'_',A,'_', A, '.SPEC' )
         ENDIF

         OPEN(UNIT= LUNTMP, FILE=SPEC_FILE, STATUS='UNKNOWN' )

c write comments

         MSG = 'VERSION_PHOTOMETRY: ' // VERSION_PHOTOMETRY(1)(1:LENV)
	 write(LUNTMP,300) MSG

         write(MSG,301) MJD
301      format('MJD:      ', F9.3)
	 write(LUNTMP,300) MSG

         write(MSG,302) NLAMBIN
302      format('NLAMBIN: ', I5)
	 write(LUNTMP,300) MSG

         write(LUNTMP,300) ' '

         if ( WR_FLAM ) then
              MSG = 'WAVE FLAM FLAMERR'
         else
              MSG = 'WAVE FLUX FLUXERR'
         endif

	 write(LUNTMP,300) MSG
300      format('# ', A)

c write spectrum
         DO 401 ilam = 1, NLAMBIN
           LAM = 0.5* ( LAMMIN_SPECTRUM(ilam) + LAMMAX_SPECTRUM(ilam) )
           LAMBIN = LAMMAX_SPECTRUM(ilam) - LAMMIN_SPECTRUM(ilam)
           F      = FLAM_SPECTRUM(ilam)
           FERR   = FLAMERR_SPECTRUM(ilam)
           if ( WR_FLUX ) then
              F    = F * LAMBIN
              FERR = FERR * LAMBIN
           endif
           WRITE(LUNTMP,440) LAM, F, FERR
440        format(F8.2, 3x, 2E14.5 )

401      CONTINUE

         CLOSE(LUNTMP)  ! close spec file
400   CONTINUE

      RETURN
      END   ! end WR_SPECTRA

C ===============================
CDECK  ID>,  END_REFORMAT. 
      SUBROUTINE END_REFORMAT

c
c Close FITS files and create README file.
c
c Jul 6 2021: don't write anything else to README so that
c             original DOCUMENTATION block appears at the top.
c             (maybe later, call function to append yaml format)
c
c Mar 7 2022: do explicit gzip
c
c -------------
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER LEN_VERS, iver, OPTMASK
      CHARACTER
     &   README_FILE*(MXCHAR_FILENAME)
     &  ,CMD*(2*MXCHAR_FILENAME)

C ----------------- BEGIN ----------------

c call C function to close out the FITS files.
      IF ( OPT_REFORMAT_FITS > 0 ) THEN
         OPTMASK = 0  ! don't gzip because gzip logic doesn't work
         CALL wr_snfitsio_end(OPTMASK)

         LEN_VERS  = INDEX(VERSION_REFORMAT_FITS,' ' ) - 1
         CMD = 'cd ' // VERSION_REFORMAT_FITS(1:LEN_VERS) //
     &        ' ; gzip *.FITS'
         print*,'   gzip output FITS files in ',
     &        VERSION_REFORMAT_FITS(1:LEN_VERS)
         call flush(6)
         CALL SYSTEM(CMD)
      ENDIF


c create README blank readme file
      CALL OPEN_REFORMAT_FILE(LUNTMP, 'README', README_FILE)
      CLOSE(LUNTMP)  ! close README file

c --- catenate original README contents for each version --------

      DO iver = 1, N_VERSION

c now just catenate the final readme with the original readme file.

         LEN_VERS  = INDEX(SNREADME_FILE(iver),' ' ) - 1
         CMD = 'cat ' // SNREADME_FILE(iver)(1:LEN_VERS)
     &         // ' >> ' // README_FILE

         CALL SYSTEM(CMD)

      ENDDO

c ---- update IGNORE file with comment on total number of IGNORE epochs
      write(LUNIGNORE2,430) NEPOCH_IGNORE_WRFITS
 430  format(/,'Total number of IGNORE epochs: ', I5)
      close(LUNIGNORE2)

      IF ( OPT_REFORMAT_FITS > 0 ) then
         print*,' Done writing reformatted FITS version: ',
     &        VERSION_REFORMAT_FITS
      ELSE
         print*,' Done writing reformatted TEXT version: ',
     &        VERSION_REFORMAT_TEXT
      ENDIF

      RETURN
      END    ! END_REFORMAT


C =========================================
CDECK  ID>,  WRS2_2. 
      SUBROUTINE WRSALT2_2()
c
c Created July 30, 2010 by R.Kessler
c Re-write SN data files into new SALT2 format with
c one file per SN.
c Output used by J. Guy's SALT2 'snfit' and 'pcafit' programs,
c version 2.3.0 and higher.
c Mainly used for SDSS data, and for simulations.
c
c
c See &SNLCINP namelist variables
c  OPT_REFORMAT_SALT2 = 2
c
c so that arbitray keys can be specified.
c
c
c Jan 25, 2013: use REAL*8 MJD8 instead of REAL*4 MJD to avoid
c               round-off error.
c
c May 20 2013: include RA and DEC in SALT2 files.
c
c Jul 8 2013: write name of ascii SNDATA file ONLY for FORMAT_TEXT=T
c
c Jul 17, 2013: write @FIELD  <list of fields>
c
c Feb 25, 2014: remove logic with ITERSE_FLUXZPT
c -----------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,WRS2COM. inserted below by ypatchy. 

c Nov 03, 2011:
c common block for translating SNANA format into SALT2 format.

      INTEGER
     &   LEN_SURVEY, LEN_INST, LEN_MAGSYS,  LEN_PREFIX
     &  ,NREPLACE, IMAP_REPLACE(MXFILT_ALL)
     &  ,NEWKEY

      CHARACTER
     &   NAMEof_INSTRUMENT*(MXCHAR_FILEWORD)
     &  ,NAMEof_MAGSYS*(MXCHAR_FILEWORD)
     &  ,NAMEof_SURVEY*(MXCHAR_FILEWORD)
     &  ,NAMEof_PREFIX*(MXCHAR_FILEWORD)
     &  ,NAMEof_REPLACE(2)*(MXCHAR_FILEWORD)
     &  ,NEWKEY_NAME(20)*(MXCHAR_FILEWORD)
     &  ,NEWKEY_ARG(20)*(MXCHAR_FILEWORD)

      COMMON / WRS2COM /
     &   LEN_SURVEY, LEN_INST, LEN_MAGSYS, LEN_PREFIX
     &  ,NREPLACE, IMAP_REPLACE, NEWKEY
     &  ,NAMEof_INSTRUMENT, NAMEof_MAGSYS
     &  ,NAMEof_SURVEY, NAMEof_PREFIX
     &  ,NAMEof_REPLACE, NEWKEY_NAME, NEWKEY_ARG

C =================================================

C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


      INTEGER
     &   EPMIN, EPMAX, EP, NEWMJD
     &  ,IFILT, IFILT_OBS, IFILT_REPLACE
     &  ,LENCID, LS, IERR, CID, ikey, L1, L2, LL, i

      REAL
     &   PEAKMJD, FLUX, FLUXERR
     &  ,ZP, ZPOFF, arg, Fscale, TMP, ERR


      REAL*8  MJD8

      LOGICAL LWR_FILT(MXFILT_OBS)

      CHARACTER
     &   cfilt1*1,  ccid*(MXCHAR_CCID)
     &  ,salt2_file*(MXCHAR_FILENAME)
     &  ,SURVEY_NAME_LOCAL*(MXCHAR_FILEWORD)
     &  ,SIMFILE*(MXCHAR_FILENAME)
     &  ,ctmp*60

C ------------ BEGIN -------------

      CCID   = SNLC_CCID

c if CCID is an integer, write in I6.6 (or I8.8) format
      read( ccid, 25 , iostat = IERR ) CID
25    format(I9)

      IF ( IERR .EQ. 0  ) THEN
         CALL CIDSTRING(CID,CCID,LENCID)
      ENDIF

c  ----------------------

      LS  = INDEX(SURVEY_NAME,' ' ) - 1
      LENCID = INDEX(CCID,' ' ) - 1

      SALT2_FILE = NAMEof_PREFIX(1:LEN_PREFIX) // '_' //
     &             CCID(1:LENCID) // '.DAT'

       LL = INDEX(SALT2_FILE,' ') - 1
       WRITE(LUNSALT2,700) SALT2_FILE(1:LL)
700    FORMAT(A)

      IF ( LSIM_SNANA ) THEN
          PEAKMJD = SIM_PEAKMJD
      ELSE
          PEAKMJD = SNLC_SEARCH_PEAKMJD
      ENDIF

      OPEN(   UNIT   = LUNDAT
     &      , FILE   = SALT2_FILE
     &      , STATUS = 'UNKNOWN'
     &           )

      IF ( NAMEof_SURVEY(1:4) .EQ.  'NULL' ) then
        SURVEY_NAME_LOCAL = SURVEY_NAME  ! SNANA survey name
      ELSE
        SURVEY_NAME_LOCAL = NAMEof_SURVEY ! user-specified survey name
      ENDIF


      ctmp = 'Translated into SALT2 format by SNANA ' // SNANA_VERSION
      write(LUNDAT,120) ctmp
      write(LUNDAT,120) ' '

      write(LUNDAT,120) 'Required variables'
      write(LUNDAT,11) 'SURVEY',   SURVEY_NAME_LOCAL
      write(LUNDAT,11) 'SN',       CCID(1:LENCID)

      write(LUNDAT,126) 'RA',    SNLC8_RA
      write(LUNDAT,126) 'DEC',   SNLC8_DEC

c ---- write field(s) - include all overlapping fields for this SN -----
      write(LUNDAT,1220)
      DO  i = 1, ISNLC_NFIELD_OVP
         LL = INDEX( SNLC_FIELD_OVPLIST(i), ' ') - 1
         write(LUNDAT,1230) SNLC_FIELD_OVPLIST(i)(1:LL)
      ENDDO
      write(LUNDAT,1240)

 1220 FORMAT('@FIELD  ', $)
 1230 FORMAT(A, '  ', $)
 1240 FORMAT(' ')

c ------------------------------------

      write(LUNDAT,12) 'Z_HELIO',  SNLC_ZHELIO
      write(LUNDAT,12) 'Z_CMB  ',  SNLC_ZCMB

      write(LUNDAT,12) 'MWEBV  ',  SNLC_MWEBV
      write(LUNDAT,12) 'MWEBV_ERR ',SNLC_MWEBV_ERR
      write(LUNDAT,13) 'DayMax  ', PEAKMJD

c --------------------------------------
c add new keys, if any are given (Dec 2010)

      DO 22 ikey = 1, NEWKEY
         L1 = INDEX(NEWKEY_NAME(ikey),' ') - 1
         L2 = INDEX(NEWKEY_ARG(ikey),' ') - 1
         write(LUNDAT,11)
     &      NEWKEY_NAME(ikey)(1:L1), NEWKEY_ARG(ikey)(1:L2)
22    CONTINUE


c Set LWR_FILT logical array for filters to write out.
c Use SNRMAX_FILT to determine if a filter is used.

      DO IFILT     = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         TMP       = SNLC_SNRMAX_FILT(ifilt)
         if ( TMP .NE. -9.0 ) then
            LWR_FILT(IFILT_OBS) = .TRUE.
         else
            LWR_FILT(IFILT_OBS) = .FALSE.
         endif
      ENDDO

c --------------------------------------
c add extra cut variables (Sep 29 2010)

      write(LUNDAT,120) ' '
      write(LUNDAT,120) 'Analysis variables'
      write(LUNDAT,30) 'SNTYPE   ',  ISNLC_TYPE
      write(LUNDAT,30) 'NOBS     ',  ISNLC_NEPOCH_USE
      write(LUNDAT,14) 'TRESTMIN ',  SNLC_TRESTMIN
      write(LUNDAT,14) 'TRESTMAX ',  SNLC_TRESTMAX
      write(LUNDAT,14) 'T0GAPMAX ',  SNLC_T0GAPMAX
      write(LUNDAT,14) 'SNRMAX   ',  SNLC_SNRMAX_SORT(1)
      write(LUNDAT,14) 'SNRMAX2  ',  SNLC_SNRMAX_SORT(2)
      write(LUNDAT,14) 'SNRMAX3  ',  SNLC_SNRMAX_SORT(3)

c write SNRMAX for each filter.
      DO IFILT     = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
         TMP       = SNLC_SNRMAX_FILT(ifilt)
         if ( LWR_FILT(ifilt_obs) ) then
            write(LUNDAT,114) 'SNRMAX_', cfilt1, TMP
         endif

      ENDDO

114   format('@', A, A, 2x, F8.3)

c to quanititative FoM, write error on flux and T0 for each band
      IF ( OPT_SETPKMJD > 0 ) THEN

        write(LUNDAT,120) ' '
        write(LUNDAT,120) 'Fitted errors => exp(dT/T1)/[1+exp(dT/T2)]'
        write(LUNDAT,120) 'ERRT0 => error on peak MJD'
        write(LUNDAT,120) 'ERRF0 => ERROR(F0)/F0 where F0 = peak flux'


        DO IFILT    = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
          if ( LWR_FILT(ifilt_obs) ) then
            ERR       = PKMJD_ERR(ifilt_obs)
            write(LUNDAT,114) 'ERRT0_', cfilt1, ERR
          endif
        ENDDO
          write(LUNDAT,12) 'ERRT0_MIN', PKMJD_ERRMIN
          write(LUNDAT,12) 'ERRT0_WGT', PKMJD_ERRWGT

        DO IFILT    = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
          if ( LWR_FILT(ifilt_obs) ) then
            ERR       = PKFLUX_ERR(ifilt_obs)/PKFLUX_FIT(ifilt_obs)
            write(LUNDAT,114) 'ERRF0_', cfilt1, ERR
          endif
        ENDDO
          write(LUNDAT,12) 'ERRF0_MIN', PKFLUX_ERRMIN
          write(LUNDAT,12) 'ERRF0_WGT', PKFLUX_ERRWGT

      ENDIF  ! end of OPT_SETPKMJD


      IF ( LSIM_SNANA ) THEN
        write(LUNDAT,120) ' '
        write(LUNDAT,120) 'SIMULATION Parameters'

c start with the exact name of the SNANA file that was translated
        IF ( FORMAT_TEXT ) THEN
          L1 = INDEX(VERSION_PHOTOMETRY(1),' ' ) - 1
          L2 = INDEX(SNDATA_FILE_CURRENT,' ' ) - 1
          SIMFILE = '$SNDATA_ROOT/SIM/' //
     &        VERSION_PHOTOMETRY(1)(1:L1) // '/' //
     &        SNDATA_FILE_CURRENT(1:L2)
          LL = INDEX(SIMFILE,' ') - 1
          WRITE(LUNDAT,11) 'SIM_SNANAFILE' , SIMFILE(1:LL)
        ENDIF

        write(LUNDAT,30)  'SIM_SNTYPE   ', SIM_GENTYPE
        write(LUNDAT,30)  'SIM_TEMPLATE_INDEX  ', SIM_TEMPLATE_INDEX
        write(LUNDAT,93)  'SIM_PEAKMJD  ', SIM_PEAKMJD
        write(LUNDAT,12)  'SIM_MWEBV    ', SIM_MWEBV
        write(LUNDAT,12)  'SIM_REDSHIFT ', SIM_REDSHIFT_CMB
        write(LUNDAT,12)  'SIM_MU       ', SIM_DLMAG

        IF ( SIM_TEMPLATE_INDEX .EQ. 0 ) THEN
          write(LUNDAT,12)  'SIM_x0 ',    SIM_SALT2x0
          write(LUNDAT,12)  'SIM_mb ',    SIM_SALT2mb
          write(LUNDAT,12)  'SIM_x1 ',    SIM_SHAPEPAR
          write(LUNDAT,12)  'SIM_c  ',    SIM_COLORPAR
          write(LUNDAT,12)  'SIM_alpha ', SIM_SHAPELAW
          write(LUNDAT,12)  'SIM_beta  ', SIM_COLORLAW
        ENDIF

        DO IFILT    = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)
          TMP       = SIM_PEAKMAG(ifilt)
          write(LUNDAT,114) 'SIM_PEAKMAG_', cfilt1, TMP
        ENDDO

      ENDIF  ! end of LSIM_SNANA

      write(LUNDAT,120) ' '
      write(LUNDAT,120) '--------------------------------------'
      write(LUNDAT,120) ' '

c ---------------------------------------
c define data columns
      write(LUNDAT,20) 'Date'
      write(LUNDAT,20) 'Flux'
      write(LUNDAT,20) 'Fluxerr'
      write(LUNDAT,20) 'ZP'
      write(LUNDAT,20) 'Filter'
      write(LUNDAT,20) 'MagSys'
      write(LUNDAT,20) 'end'

11    format('@', A, 2x, A)
12    format('@', A, 2x, F8.5)
13    format('@', A, 2x, F9.3, 2x, '1')
14    format('@', A, 2x, F7.2)
20    format('#', A, ' : ' )
30    format('@', A, 2x, I5)
93    format('@', A, 2x, F9.3)
126   format('@', A, 2x, F12.6)

120   format('# ! ', A )

c write observations.

      DO 301 NEWMJD = 1, ISNLC_NEWMJD_STORE
          EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
          EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

          DO 302 EP = EPMIN, EPMAX

            IFILT_OBS     = ISNLC_IFILT_OBS(ep)
            IFILT_REPLACE = IMAP_REPLACE(IFILT_OBS)

c  skip obs that are cut in SNRECON (Jan 2, 2012)
            if ( .not. LWR_FILT(ifilt_obs) ) GOTO 302


            IF ( IFILT_REPLACE .GT. 0 ) THEN
               cfilt1 = filtdef_string(ifilt_replace:ifilt_replace)
            ELSE
               cfilt1 = filtdef_string(ifilt_obs:ifilt_obs)
            ENDIF

            ZPOFF   = MAGOBS_SHIFT_ZP_FILT(ifilt_obs)
            MJD8    = SNLC8_MJD(EP)

            ZP  = SNGL(ZEROPOINT_FLUXCAL_DEFAULT) + ZPOFF
            arg = 0.4*ZPOFF

            Fscale  = 10.0**ARG

c get fluxes in native system (i.e., undo AB offsets)
            Flux    = Fscale * SNLC_FLUXCAL(EP)
            Fluxerr = Fscale * SNLC_FLUXCAL_ERRTOT(EP)
            WRITE(LUNDAT,330) MJD8, FLUX, FLUXERR, ZP
     &          , NAMEof_INSTRUMENT(1:LEN_INST)
     &          , cfilt1
     &          , NAMEof_MAGSYS(1:LEN_MAGSYS)

302      CONTINUE  ! EP
301   CONTINUE  ! NEWMJD

330   FORMAT(F9.3, 2x, 2G14.6, 1x, F7.3, 3x,A,'::',A,1x,A )

      CLOSE ( LUNDAT )

      RETURN
      END  ! end of WRSALT2_2


C ============================
CDECK  ID>,  MADABORT. 
      SUBROUTINE MADABORT(funname,c1err,c2err)
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST

      character funname*(*)  ! name of function calling MADABORT
      character c1err*(*), c2err*(*) ! two error messages
      INTEGER ISEV_FATAL, IPROMPT, LENF, LEN1, LEN2
      PARAMETER ( ISEV_FATAL = 4, IPROMPT=0 )

      EXTERNAL ERRMSG
      INTEGER  LENSTR
c ----------------- BEGIN --------------
      LENF = LENSTR(funname//' ')
      LEN1 = LENSTR(c1err)
      LEN2 = LENSTR(c2err)
      call errmsg(ISEV_FATAL, IPROMPT,
     &     funname(1:LENF)//char(0),
     &     c1err(1:LEN1)//char(0),
     &     c2err(1:LEN2)//char(0),
     &     LENF, LEN1, LEN2 )

      RETURN
      END

C =============================
CDECK  ID>,  LENSTR. 
      INTEGER FUNCTION LENSTR(string)
c Created Dec 17 2019
c STRING = 'Hi, what is this.' --> LENSTR = 17
c
      IMPLICIT NONE
      CHARACTER STRING*(*)
      INTEGER LENTOT, LEN, i
C ---------- BEGIN -------------
      LENTOT = index(string,' ', back = .TRUE. ) - 1
      DO i = 1, LENTOT
        IF ( STRING(i:i) .NE. ' ' ) LEN=i
      ENDDO
      LENSTR = LEN
      RETURN
      END


C ======================================
CDECK  ID>,  CHCKLINE_ARGS. 
      SUBROUTINE CHECK_LINE_ARGS()
c
c Feb 7, 2007
c Check that all NLINE_ARG command-line args
c were used. If any were not used, then give
c error message and abort.
c
c Aug 2020: use MADABORT for consistent error messaging
c


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER i, LL, NBAD
      CHARACTER FNAM*16, ARG*(MXCHAR_ARG)
C ------------------ BEGIN --------------

      NBAD = 0
      FNAM = 'CHECK_LINE_ARGS'

      DO i = 2, NLINE_ARGS

         if ( .NOT. USE_LINE_ARGS(i) ) then
            NBAD = NBAD + 1

            if ( NBAD .EQ. 1 ) then
              CALL PRINT_PREABORT_BANNER(FNAM//char(0),20)
            endif
            CALL GETARG(i,ARG)
            LL = INDEX(ARG, ' ' ) - 1
            print*,' ERROR: Detected un-used command-line argument: ',
     &                 '"' , ARG(1:LL), '"'
         endif
      ENDDO

      IF ( NBAD .GT. 0 ) THEN
         write(C1ERR,61) NBAD
61       format('Detected ', I3,' unknown command line arguments')
         C2ERR = 'Check args ERROR messages above'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

      RETURN
      END


C ================================================
CDECK  ID>,  INIT_SNVAR. 
      SUBROUTINE INIT_SNVAR()
c
c Init some SN variables.
c Called once at beginning of program.
c See INIT_SNLC to initilaize each SN.
c
c Feb 19 2014: abort if SNDATA_ROOT is not defined.
c Jan 16 2019: init EXIT_ERRCODE
c ---------------------------------------------------

      IMPLICIT NONE

c include everything except the memory hogging SNLCCOM


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

c +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


C +CDE,EARLYCOM. inserted below by ypatchy. 

      REAL DT_SAMENIGHT
ccc   PARAMETER (DT_SAMENIGHT = 0.333) ! same night within 1/3 day = 8 hr
      PARAMETER (DT_SAMENIGHT = 0.400) ! same night within 0.4 day

c variables for selecting the early part of a light curve
      INTEGER    NOBS_EARLYLC, NNIGHT_EARLYLC
      INTEGER    NPHOTMASK_START_EARLYLC
      REAL       NSNR_START_EARLYLC
      REAL       MJDLAST_EARLYLC, MJDLAST_SELECT

      COMMON / EARLYCOM /
     &   NOBS_EARLYLC, NNIGHT_EARLYLC,
     &   NPHOTMASK_START_EARLYLC, NSNR_START_EARLYLC,
     &   MJDLAST_EARLYLC, MJDLAST_SELECT

c parameters parsed from EARLYLC_STRING:
      INTEGER  MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, PHOTMASK_EARLYLC,
     &         NDAYADD_EARLYLC, PHOTMASK_START_EARLYLC
      REAL  SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, SNR_START_EARLYLC
      CHARACTER  FILTERS_EARLYLC*(MXFILT_ALL)

      COMMON / EARLYINP /
     &   MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, NDAYADD_EARLYLC
     &  ,FILTERS_EARLYLC
     &  ,SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, PHOTMASK_EARLYLC
     &  ,PHOTMASK_START_EARLYLC, SNR_START_EARLYLC


C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


      INTEGER icut, i, ibit, itype, ipar, ifilt, LM,istat
      INTEGER LL, LL_SNANA, NWD, LL_HOST
      CHARACTER ENVtemp*400, MACH*40, FNAM*12

c function
      INTEGER FILTINDX, EXEC_CIDMASK, STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS, SET_EXIT_ERRCODE

C ---------------- BEGIN ------------

      FNAM = 'INIT_SNVAR'

      EXIT_ERRCODE = EXIT_ERRCODE_SNFIT
      CALL SET_EXIT_ERRCODE(EXIT_ERRCODE) ! for C function aborts

      IDSURVEY = -9 ;  IDSUBSURVEY=-9
      NCALL_SNANA_DRIVER  = 0

      CALL PRBANNER ( " INIT_SNVAR: Init variables." )

      FORMAT_TEXT    = .FALSE.
      FORMAT_FITS    = .FALSE.

      ISJOB_SNANA = .FALSE.
      ISJOB_SNFIT = .FALSE.
      ISJOB_PSNID = .FALSE.
      ISJOB_BATCH = .FALSE.

      NEPOCH_TOT = 0
      NEPOCH_USE = 0
      NEPOCH_CUT = 0
      NEPOCH_BADPHOT     = 0
      NEPOCH_BADPHOT_SUM = 0

      INTERP_OPT  = INTERP_LINEAR  ! used by simulation

c define filter indices for Legacy filters
      IFILT_SDSS_u = FILTINDX("u ")
      IFILT_SDSS_g = FILTINDX("g ")
      IFILT_SDSS_r = FILTINDX("r ")
      IFILT_SDSS_i = FILTINDX("i ")
      IFILT_SDSS_z = FILTINDX("z ")
      IFILT_BESS_U = FILTINDX("U ")
      IFILT_BESS_B = FILTINDX("B ")
      IFILT_BESS_V = FILTINDX("V ")
      IFILT_BESS_R = FILTINDX("R ")
      IFILT_BESS_I = FILTINDX("I ")
      IFILT_BESS_BX = FILTINDX("X ")
      IFILT_Y = FILTINDX("Y ")
      IFILT_J = FILTINDX("J ")
      IFILT_H = FILTINDX("H ")
      IFILT_K = FILTINDX("K ")

      SURVEY_NAME    = ''
      SUBSURVEY_NAME = ''
      SUBSURVEY_NAME_LIST=''

      SURVEY_FILTERS = ''
      FREEZE_SURVEY_FILTERS = .FALSE.
      EXIST_BXFILT_OBS      = .FALSE.
      EXIST_BXFILT_REST     = .FALSE.

      NFILTDEF_SURVEY = 0
      NFILTDEF_READ   = 0
      NFILTDEF_REST   = 0

      NFILTDEF_IGNORE_REST = 0

      DO ifilt = 1, MXFILT_OBS
          IFILTDEF_MAP_SURVEY(ifilt) = -9
          IFILTDEF_MAP_REST(ifilt)   = -9
          IFILTDEF_IGNORE_REST(ifilt) = -9
      ENDDO

      DO ifilt = 1, MXFILT_ALL

          IFILTDEF_INVMAP_SURVEY(ifilt)  = -9
          IFILTDEF_INVMAP_REST(ifilt)    = -9

          MAGOBS_SHIFT_PRIMARY_FILT(ifilt)  = 0.0
          MAGOBS_SHIFT_ZP_FILT(ifilt)       = 0.0
          MAGOBS_SHIFT_ZP_USER(ifilt)       = 0.0
          MAGREST_SHIFT_PRIMARY_FILT(ifilt) = 0.0
          MAGREST_SHIFT_ZP_FILT(ifilt)      = 0.0
          MAGREST_SHIFT_ZP_USER(ifilt)      = 0.0
          FILTOBS_ZPOFF_SNPHOT(ifilt)       = 0.0

          FILTOBS_TRANSMAX(ifilt)         =  0.0
          FILTOBS_LAMAVG(ifilt)           = -9.0
          FILTOBS_LAMRMS(ifilt)           = -9.0
          FILTOBS_LAMRANGE(1,ifilt)       = -9.0
          FILTOBS_LAMRANGE(2,ifilt)       = -9.0
          FILTOBS_LAMSHIFT(ifilt)         =  0.0
          NLAMBIN_FILTOBS(ifilt)          =  0

          FILTREST_TRANSMAX(ifilt)         =  0.0
          FILTREST_LAMAVG(ifilt)           = -9.0
          NLAMBIN_FILTREST(ifilt)          =  0
          FILTREST_LAMRANGE(1,ifilt)       = -9.0
          FILTREST_LAMRANGE(2,ifilt)       = -9.0

          FILTOBS_NAME(ifilt)       = ''
          SURVEY_FILT_NAME(ifilt)   = 'NONE'
          LFILTDEF_OBS(ifilt)       = .FALSE.
          LFILTDEF_REST(ifilt)      = .FALSE.
          LFILTDEF_NONSURVEY(ifilt) = .FALSE.
          LFILTDEF_SNRMAX(ifilt)    = .TRUE.  ! use all filters by default

          FUDGE_FLUXCAL_ERROR_FILT(ifilt)   =  0.0
          FUDGE_FLUXCAL_ERRPIX_FILT(ifilt)  =  0.0
          FUDGE_FLUXCAL_OFFSET_FILT(ifilt)  =  0.0
          FUDGE_FLUXERR_SCALE_FILT(ifilt)   =  1.0 ! Feb 2020
          FUDGE_MAG_ERROR_FILT(ifilt)       =  0.0
          FUDGE_MAG_COVERR_FILT(ifilt)      =  0.0

      END DO

c extract SNDATA_ROOT and SNANA_DIR  env variables

      CALL GETENV ( 'HOST',     ENVtemp )
      LL = INDEX ( ENVtemp , ' ' ) - 1
      HOST_MACHINE = ENVtemp(1:LL)

      CALL GETENV ( 'MACHTYPE', ENVtemp )
      LM = INDEX ( ENVtemp , ' ' ) - 1
      MACH = ENVtemp(1:LM)

      print*,'  HOST MACHINE = ', HOST_MACHINE(1:LL),
     &      '   (',MACH(1:LM),')'

      CALL GETENV ( 'SNDATA_ROOT', ENVtemp )
      LL = INDEX ( ENVtemp , ' ' ) - 1

      IF ( LL > MXCHAR_PATH ) then
         write(C1ERR,61) 'SNDATA_ROOT', LL
         write(C2ERR,62) MXCHAR_PATH
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF
61       FORMAT('LEN($', A, ') = ',I3,' is too long')
62       format('MXCHAR_PATH = ', I3)
      if ( LL .EQ. 0 ) then
         C1ERR = 'SNDATA_ROOT is not defined.'
         C2ERR = 'Check your snana setup.'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

      SNDATA_ROOT = ENVtemp(1:LL)
      print*,'  SNDATA_ROOT = ', SNDATA_ROOT(1:LL)

c - - - - -
      CALL GETENV ( 'SNANA_DIR', ENVtemp )
      LL = INDEX ( ENVtemp , ' ' ) - 1
      IF ( LL > MXCHAR_PATH ) then
         write(C1ERR,61) 'SNANA_DIR', LL
         write(C2ERR,62) MXCHAR_PATH
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

      SNANA_DIR = ENVtemp(1:LL)
      print*,'  SNANA_DIR = ', SNANA_DIR(1:LL)


      N_SNFILE      = 0
      N_SNFILE_LAST = 0

      N_SNLC_PROC     = 0
      N_SNLC_CUTS     = 0
      N_SNLC_SPEC     = 0
      N_SNLC_FIT      = 0
      N_SNLC_FITCUTS  = 0
      N_SNLC_COVFIX   = 0
      N_SNLC_PLOT     = 0
      N_SNHOST_ZSPEC  = 0
      N_SNHOST_ZPHOT  = 0
      N_DUPLICATE_CID = 0
      N_DUPLICATE_MJD = 0
      NSTORE_DUPLICATE_MJD = 0

      ABSO_OFFSET = 0
      ABSO_INDEX  = 0

      DO itype = -1, MXTYPE
        NPASSCUT_FIT(itype) = 0
      DO ibit  = 1, NCUTBIT_SNLC+1
        NPASSCUT_INCREMENT(itype,ibit) = 0
      ENDDO
      ENDDO

      LSIM_SNANA   = .FALSE.  ! snana sim
      LSIM_MAGOBS  = .FALSE.
      ISJOB_SIM    = .FALSE.

      NACCEPT_Z    = 0
      NACCEPT_ZERR = 0
      NACCEPT_CID  = 0
      NACCEPT_TYPE = 0
      DO icut = 1, NCUTBIT
        NACCEPT_CUT(icut) = 0
      ENDDO

c init HIDKCOR array to 0

      ISTAT = EXEC_CIDMASK(0,MXCID_CHECK)  ! init CID bit-mask

      DO IPAR = 1, MXFITPAR
         ERRMAX_BAD(ipar) = 1.0E-4  ! err < ERRMAX_BAD is labelled bad
      ENDDO

      SIMNAME_MODEL        = 'SIMNULL0'
      SIMNAME_SHAPEPAR     = 'SIM_SHAPE'  ! changed from SIMSHAPE (4/11/2017)
      SIMNAME_SHAPELAW     = 'SIMNULL1'  ! each SIMNULL has unique name
      SIMNAME_COLORPAR     = 'SIMNULL2'
      SIMNAME_COLORLAW     = 'SIMNULL3'
      SIMNAME_SNRMON       = 'NONE'

      SIMOPT_MWCOLORLAW = -9
      SIMOPT_MWEBV      = -9

      DO ifilt = 1, MXFILT_OBS
         SIM_EXPOSURE_TIME(ifilt)  = 1.0
      ENDDO

      SIMLIB_FILENAME = ""
      SIMLIB_MSKOPT   = 0

      DO ibit = 1, NCUTBIT
         CUTWIN_VAR(1,ibit) = -CUTVAL_OPEN
         CUTWIN_VAR(2,ibit) = +CUTVAL_OPEN
      ENDDO
         CUTWIN_VAR(1,CUTBIT_NMJD_INCLUDE) = 0.99

      NEPOCH_IGNORE =  0
      EPOCH_IGNORE_LASTFILE = ''

cc      ZPOFF_FILE    = 'NULL'  ! NULL => use offsets in hid 292
      USERTAGS_FILE = ''
      VPEC_FILE            = ''
      HEADER_OVERRIDE_FILE = ''
      SIM_HEADER_OVERRIDE_FILE = ''


      NPAR_SIMSED      = 0
      NPAR_PySEDMODEL  = 0
      NPAR_LCLIB       = 0

      NPAR_SIM_HOSTLIB = 0

      C1ERR = ' '
      C2ERR = ' '

      DO_FLUXERRCALC = .FALSE.

      NFIT_PKMJD = 0

      NVAR_PRIVATE = 0
      DO i = 1, MXVAR_PRIVATE
        PRIVATE_KEYWORD(i)  = 'UNKNOWN'
        PRIVATE_VARNAME(i)  = 'UNKNOWN'
        PRIVATE_VALUE(i)    = PRIVATE_NULL
        PRIVATE_CUTWIN(1,i) = -CUTVAL_OPEN
        PRIVATE_CUTWIN(2,i) = +CUTVAL_OPEN
      ENDDO

      NCUT_PRIVATE = 0
      DO i = 1, MXCUT_PRIVATE
         PRIVATE_CUTWIN_STRING(i) = ''
         USE_PRIVATE_CUTWIN(i)    = 0
      ENDDO
      PRIVATE_VARNAME_READLIST = ''

      SIMVAR_CUTWIN_STRING  = ''
      NSIMVAR_CUTWIN        = 0

      EARLYLC_STRING        = ''
      REQUIRE_EPOCHS_STRING =  ''
      DUMP_STRING           = ''

c init HOST logicals
      EXIST_SNHOST_ZPHOT    = .FALSE.
      EXIST_SNHOST_LOGMASS  = .FALSE.
      EXIST_SNHOST_LOGSFR   = .FALSE.
      EXIST_SNHOST_LOGsSFR  = .FALSE.
      EXIST_SNHOST_COLOR    = .FALSE.
      EXIST_SNHOST_MAGOBS   = .FALSE.
      EXIST_SNHOST_SB       = .FALSE.
      EXIST_SNHOST_ANGSEP   = .FALSE.
      EXIST_SNHOST_DDLR     = .FALSE.
      EXIST_SNHOST_CONFUSION= .FALSE.

c misc.
      NONSURVEY_FILTERS = ''
      FILTER_REPLACE    = ''
      FILTLIST_LAMSHIFT = ''

      NVAR_NEARNBR = 0
      FLAG_NEARNBR = NNFLAG_IGNORE

      DO i = 1, MXFITSTORE
         PARNAME_STORE(i) = ''
         PAROPT_STORE(i)  = 0
      ENDDO

      CALL FLUSH(6)

      NWD = STORE_PARSE_WORDS(-1, ""//char(0), FNAM//char(0), 2, 12);

      RDFLAG_SPECTRUM = .FALSE.

      RETURN
      END   ! end of INIT_SNVAR

C ===============================================
CDECK  ID>,  NNRDINP. 
      INTEGER FUNCTION SNANA_NEARNBR_RDINPUT()

c Created Apr 2013 by R.Kessler
c Check NEARNBR_XXX parameters from optioanl &NNINP namelist,
c and run initialization functions in sntools_nearnbr.c.
c This is a generic interface for any snana program so that
c the NN inputs can go into the same nml file as the other
c inputs.
c
c Returns NVAR
c   = number of variables to analyze (flag that NN option is set)
c   = 0 -> NN option is NOT selected (flag to ignore NN option)
c
c Jun 12 2019:
c   pass TRUETYPE_SNIa to NEARNBR_SET_TRUETYPE().
c   Needed if SCALE_NON1A != 1.
c
c Jan 29 2020: abort if TRAINFILE_PATH is set, but TRAINFILE_LIST is not.
c
c -----------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


      INTEGER   iocheck, LSTR,  LV, NVAR, NVAL, ISPLIT, N_IGNORE
      INTEGER   jskip, j, iwd, ign, NWD, MSKOPT, TRUETYPE_SNIa
      CHARACTER
     &   STRING*(MXCHAR_FILENAME)
     &  ,VARLIST_IGNORE(NN_MXVAR)*(MXCHAR_FILEWORD)
     &  ,PATH*(MXCHAR_FILENAME)
     &  ,FNAM*24, VARNAME*(MXCHAR_FILEWORD)
     &  ,cwd*(MXCHAR_FILEWORD), c1, cMODE*8
     &  ,name_forC*(MXCHAR_FILENAME)

      LOGICAL   INPUT_ISVARNAME(4*NN_MXVAR)
      LOGICAL   IS_TRAINPATH, IS_TRAINFILE
      CHARACTER INPUT_VARNAME(4*NN_MXVAR)*(MXCHAR_FILEWORD)
      REAL*8    INPUT_VALUE(4*NN_MXVAR)
      REAL*8    SEPMAX(3), RATIO

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------- BEGIN -----------

      SNANA_NEARNBR_RDINPUT = 0
      FNAM = 'SNANA_NEARNBR_RDINPUT'

c init &NNINP values.
      NEARNBR_TRAINFILE_PATH    = ' '
      NEARNBR_TRUETYPE_VARNAME  = ' '
      NEARNBR_SEPMAX_VARDEF     = ' '
      NEARNBR_SEPMAX_IGNORE     = ' '
      NEARNBR_TRAINFILE_LIST    = ' '
      NEARNBR_TRAIN_ODDEVEN     = .FALSE.
      NEARNBR_TRAINFILE_SCALE_NON1A = 1.0

      NN_ITYPE_FIX    = -99
      NN_ITYPE_SNIa   = 1

c init sums for each best-type
      NNSUM_UNKNOWN=0; NNSUM_IA=0;  NNSUM_NON1A=0

c re-open nml file
      OPEN (UNIT=LUNNML, file=nmlfile, status='OLD',ERR=900 )

c try reading NNINP; if not there, just return quietly.
      READ ( LUNNML, NML = NNINP, ERR = 900, IOSTAT = iocheck )
      CLOSE ( UNIT = LUNNML )
      if ( iocheck .NE. 0 ) return

c make sure required output file (root or hbook) is specified
c to make NN-specific 1D and 2D histograms.
      if ( .NOT. USE_TABLEFILE ) then
         C1ERR = 'Must specify HFILE_OUT or ROOTFILE_OUT in &SNLCINP'
         C2ERR = 'to create required histograms for NN-training.'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

c namelist &NNINP  exists ==> read it.
      CALL PRBANNER ( " FOUND and READ &NNINP NAMELIST. " )
      WRITE ( 6 , NML = NNINP )
      CALL FLUSH(6)

c check for command-line override
      CALL NNINP_OVERRIDE()

      IS_TRAINPATH = ( NEARNBR_TRAINFILE_PATH .NE. ' ' )
      IS_TRAINFILE = ( NEARNBR_TRAINFILE_LIST .NE. ' ' )

c make sure there is a training file to continue
      IF ( .not. IS_TRAINFILE ) THEN
         IF ( IS_TRAINPATH ) THEN
           c1err = 'NEARNBR_TRAINFILE_PATH is set, '
           c2err = 'but NEARNBR_TRAINFILE_LIST is not.'
           CALL  MADABORT(FNAM, C1ERR, C2ERR)
         ENDIF
         RETURN
      ENDIF

c ----------------------------------------------
c call init functions in sntools_nearnbr.c

      CALL NEARNBR_INIT()  ! C function

      IF ( IS_TRAINPATH  ) THEN
        CALL SNANA_NEARNBR_RDPATH(PATH)  ! return PATH
        LSTR = INDEX(PATH,' ') - 1
        CALL NEARNBR_SET_TRAINPATH(PATH(1:LSTR)//char(0), LSTR)
      ENDIF

c -----------------------------
      IF ( NEARNBR_TRAIN_ODDEVEN ) THEN
         CALL NEARNBR_SET_ODDEVEN()  ! Apr 5 2019
         print*,'   ODDEVEN flag -> Select even CIDs'
         call flush(6)
      ENDIF

c init TRAINFILE

      STRING = NEARNBR_TRAINFILE_LIST
      LSTR = INDEX(STRING,' ') - 1
      CALL NEARNBR_SET_TRAINFILE(STRING(1:LSTR)//char(0),
     &            NEARNBR_TRAINFILE_SCALE_NON1A, LSTR)

c ----------------
c set variable name with TRUETYPE

      STRING = NEARNBR_TRUETYPE_VARNAME
      LSTR = INDEX(STRING,' ') - 1
      TRUETYPE_SNIa = 1 ! beware this is hard-coded
      CALL NEARNBR_SET_TRUETYPE(STRING(1:LSTR)//char(0),
     &                          TRUETYPE_SNIa, LSTR)

c get list of sepmax variables to IGNORE
      N_IGNORE = 0
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      IF ( NEARNBR_SEPMAX_IGNORE .NE. ' ' ) THEN
         LSTR      = INDEX(NEARNBR_SEPMAX_IGNORE,' ') -1
         NAME_forC = NEARNBR_SEPMAX_IGNORE(1:LSTR)//char(0)
         N_IGNORE = STORE_PARSE_WORDS(MSKOPT,NAME_forC,
     &                 FNAM//char(0), LSTR, 24)
         do jskip = 1, N_IGNORE
            CALL get_PARSE_WORD_fortran(jskip,
     &           VARLIST_IGNORE(jskip),LSTR)  ! returned
            write(6,678) VARLIST_IGNORE(jskip)
 678        format(T15,'Will IGNORE SEPMAX variable ' , A)
            call flush(6)
         enddo
      ENDIF

c -----------------------------
c break up each SEPMAX strings into VARNAME and SEPMAX(3) = MIN,MAX,BIN
c Example 1:  NEARNBR_SEPMAX_VARDEF = 'z .10' ->
c             VARNAME = 'z' and SEPMAX(3) = 0.10, 0, 0
c
c Example 1:  NEARNBR_SEPMAX_VARDEF = 'z .04 .20 .01' ->
c             VARNAME = 'z' and SEPMAX(3) = 0.04, 0.20, 0.01
c
c IGNORE any variable on the IGNORE list ... allows removing
c variables with FITOPT option in split_and_fit.

      LSTR = INDEX(NEARNBR_SEPMAX_VARDEF,' ', BACK=.TRUE.) - 1
      NAME_forC = NEARNBR_SEPMAX_VARDEF(1:LSTR)//char(0)
      NWD = STORE_PARSE_WORDS(MSKOPT,NAME_forC,
     &                 FNAM//char(0), LSTR, 24)
c --------------------------------------------------------------
c check which words are variables names (i.e., strings) or values;
c check is based on first char of each word. Fill INPUT_XXX arrays.

      NVAR = 0 ;  NVAL = 0

      DO 100 iwd = 1, NWD
         INPUT_ISVARNAME(iwd) = .FALSE.
         INPUT_VALUE(iwd)     = 99999.
         INPUT_VARNAME(iwd)   = 'NULL'

         CALL get_PARSE_WORD_fortran(iwd,cwd,LSTR)

         c1   = cwd(1:1)
         j    = index('0123456789.', c1)
         if ( j <= 0 ) then
            INPUT_ISVARNAME(iwd) = .TRUE.
            INPUT_VARNAME(iwd)   = cwd
            NVAR = NVAR + 1
         else
            READ(cwd,*) INPUT_VALUE(iwd)
            NVAL = NVAL + 1
         endif

        if ( NVAR > NN_MXVAR ) then
           c1err = 'Too many SEPMAX variables in NEARNBR_SEPMAX_VARDEF'
           c2err = 'See NN_MXVAR in snana.car'
           CALL  MADABORT(FNAM, C1ERR, C2ERR)
        endif


 100  CONTINUE

c --------------------------------------------------------------
c if NVAL = NVAR, then we do analysis with fixed sepmax params.
c if NVAL = 3*NVAR then we do training.
c Abort on any other ratio.


      RATIO = 0.0
      IF ( NVAR > 0 ) RATIO = DBLE(NVAL)/DBLE(NVAR)
      IF ( RATIO == 1.0 ) THEN
         FLAG_NEARNBR = NNFLAG_APPLY ; jskip = 2
          cMODE = 'ANALYSIS'
      ELSE IF ( RATIO == 3.0 ) THEN
         FLAG_NEARNBR = NNFLAG_TRAIN ; jskip = 4
         cMODE = 'TRAINING'
      ELSE
         write(c1err,651) NVAL, NVAR, RATIO
 651     format('Invalid ratio [NVAL=',I3,'/NVAR=',I3,'] =',F5.2,2x,
     &       '(must be 1 or 3)'  )
         c2err = 'Check NEARNBR_SEPMAX_VARDEF in &NNINP.'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

c ----------------------------------------------
c Loop over VARDEF words again (with jskip = 2 or 4), and call
c NEARNBR_SET_SEPMAX (in sntools_nearnbr.c) for each variable.

      NVAR = 0
      DO 300 iwd = 1, NWD, jskip

         VARNAME   = INPUT_VARNAME(iwd)

c Dec 6 2014: skip any on the ignore list
         do ign = 1, N_IGNORE
            if ( VARLIST_IGNORE(ign) .EQ. VARNAME ) goto 300
         enddo

         NVAR = NVAR + 1
         NEARNBR_SEPMAX_VARNAME(NVAR) = VARNAME(1:20) ! store globally

         if ( FLAG_NEARNBR == NNFLAG_APPLY ) then
            SEPMAX(1) = INPUT_VALUE(iwd+1)
            SEPMAX(2) = 0.0
            SEPMAX(3) = 0.0
         elseif ( FLAG_NEARNBR == NNFLAG_TRAIN ) then
            SEPMAX(1) = INPUT_VALUE(iwd+1)
            SEPMAX(2) = INPUT_VALUE(iwd+2)
            SEPMAX(3) = INPUT_VALUE(iwd+3)
         else
            write(c1err,661) FLAG_NEARNBR
 661        format('Invalid FLAG_NEARNBR = ',I6,' . ' )
            c2err = 'Should be either 1(ANAL-mode) or 2(TRAIN mode).'
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         endif

         LV = INDEX(VARNAME,' ') - 1
         CALL NEARNBR_SET_SEPMAX(VARNAME(1:LV)//char(0), SEPMAX, LV)
 300  CONTINUE

      SNANA_NEARNBR_RDINPUT = NVAR  ! return arguement

c --------------------------------------
c 2nd init after passing all info

      CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! climb out of MONINIT

c set ISPLIT so that certain plots are made only on first split-job
      ISPLIT = MAX(JOBSPLIT(1),JOBSPLIT_EXTERNAL(1))

c init again after variable list is defined
      CALL NEARNBR_INIT2(ISPLIT)    ! C code in sntools_nearnbr.c

      RETURN
c -------------

900   CONTINUE
      C1err = 'Could not read  &NNINP namelist '
      C2err = 'Check ' // nmlfile(1:60)
      CALL  MADABORT(FNAM, C1ERR, C2ERR)


      RETURN
      END    ! end of SNANA_NEARNBR_RDINPUT


C ==================================
CDECK  ID>,  NNRDPATH. 
      SUBROUTINE SNANA_NEARNBR_RDPATH(PATH)

c Created Dec 2014
c
c Return PATH of trainfile for NN.
c If  NEARNBR_TRAINFILE_PATH has no dot, then assume
c it's a path and return PATH = NEARNBR_TRAINFILE_PATH.
c
c However, if NEARNBR_TRAINFILE_PATH has a dot then
c assume it's a file containing a list of
c
c  VERSION:  [VERSION] [PATH]
c
c and read the file and return PATH associated with VERSION_PHOTOMETRY.
c Note that the subroutine inputs (VERSION_PHOTOMETRY and
c NEARNBR_TRAINFILE_PATH) are passed via globals. This file
c option is intended to be used with a NN-pipeline script.
c
c Aug 28 2016:  call ENVreplace(NEARNBR_TRAINFILE_PATH)

      IMPLICIT NONE

      CHARACTER PATH*(*) ! output path


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
c +CDE,PARSECOM.

      INTEGER JDOT, JSLASH,  LREF, LTMP, NFOUND
      CHARACTER
     &    VER_TMP*(MXCHAR_VERSION)
     &   ,VER_REF*(MXCHAR_VERSION)
     &   ,PATH_TMP*200, KEY*20
     &   ,FNAM*22, C1ERR*80, C2ERR*80

C --------------- BEGIN -------------


      FNAM = 'SNANA_NEARNBR_RDPATH'

      call ENVreplace(NEARNBR_TRAINFILE_PATH) ! Aug 28 2016

      PATH   = 'UNKNOWN'
      JDOT   = INDEX(NEARNBR_TRAINFILE_PATH,'.', BACK=.TRUE.)
      JSLASH = INDEX(NEARNBR_TRAINFILE_PATH,'/', BACK=.TRUE.)

c if last dot is before last slash, then it's a path already.
      IF ( JDOT < JSLASH ) THEN
         PATH = NEARNBR_TRAINFILE_PATH
         RETURN
      ENDIF

c if last dot is after last slash, it's a file to be parsed below.

c if we get here, read file to get path

      print*,'   Read NEARNBR_TRAINFILE_PATH from '
      print*,'   ', NEARNBR_TRAINFILE_PATH

      VER_REF = VERSION_PHOTOMETRY(1)
      LREF  = INDEX(VER_REF,' ' ) - 1
      NFOUND = 0

      OPEN ( UNIT=LUNTMP, FILE=NEARNBR_TRAINFILE_PATH,
     &       STATUS='OLD', ERR=900 )

c - - - - - - -
c Note that PATH_TMP must be in quotes to handle the slash symbol.

44    READ(LUNTMP,*, END=400) KEY, VER_TMP, PATH_TMP

      LTMP  = INDEX(VER_TMP,' ') - 1
      IF ( LTMP .NE. LREF ) GOTO 44
      IF ( VER_TMP(1:LTMP) .NE. VER_REF(1:LREF) ) GOTO 44

      NFOUND = NFOUND + 1
      PATH   = PATH_TMP

      GOTO 44
c - - - - - - -

400   CLOSE(UNIT=LUNTMP)

c make sure we found the matching version<->path once and only once.

      IF ( NFOUND .NE. 1 ) THEN
        write(c1err,661) NFOUND
661     format('Found TRAINFILE_PATH ',I2,' times')
        c2err = 'for VERSION = ' // VER_REF(1:LREF)
        CALL MADABORT(FNAM, c1err, c2err)
      ENDIF

      RETURN

c -----------------------------
900   C1ERR = 'Could not open NEARNBR_TRAINFILE_PATH file:'
      C2ERR = NEARNBR_TRAINFILE_PATH(1:72)
      CALL MADABORT(FNAM, c1err, c2err)
      RETURN

      END  ! end of SNANA_NEARNBR_RDPATH


C ===========================================
CDECK  ID>,  NNTRAIN_END. 
      SUBROUTINE SNANA_NEARNBR_TRAIN_END()

c Created Apr 24 2014 by R.Kessler
c Print message on how to finish training.
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LENF
      CHARACTER codeName*20

C ----------- BEGIN --------

      codeName = 'nearnbr_maxFoM.exe'

      CALL PRINT_NN_BANNER()

      print*,'   To optimize SEPMAX variables and finish NN training, '
      print*,'   run the following command: '

      if ( USE_TABLEFILE_HBOOK ) then
         LENF = index(HFILE_OUT,' ') - 1
         write(6,20) codeName, HFILE_OUT(1:LENF)
      endif

      if ( USE_TABLEFILE_ROOT ) then
         LENF = index(ROOTFILE_OUT,' ') - 1
         write(6,20) codeName, ROOTFILE_OUT(1:LENF)
      endif
 20   format(T7,A, 2x, A)

      CALL PRINT_NN_BANNER()

      RETURN
      END    ! SNANA_NEARNBR_TRAIN_END

C ==========================
CDECK  ID>,  PRNN_BANNER. 
      SUBROUTINE PRINT_NN_BANNER
      print*,' '
      print*,'# NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN'
      print*,'# NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN-NN'
      print*,' '
      call flush(6)
      RETURN
      END

C ===========================================
CDECK  ID>,  NNAPPLY_END. 
      SUBROUTINE SNANA_NEARNBR_APPLY_END()

c Created Apr 24 2014 by R.Kessler
c Print message on how to finish training.
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa

c+CDE,SNCUTS.
c+CDE,SNLCINP.

C -------------- BEGIN -------------

      CALL PRINT_NN_BANNER()

      print*,'  NN-APPLY Statistics Summary: '
      print*,'     NEVT(NN-unknown) = ', NNSUM_UNKNOWN
      print*,'     NEVT(NN-Ia)      = ', NNSUM_IA
      print*,'     NEVT(NN-NON1A)   = ', NNSUM_NON1A

      CALL PRINT_NN_BANNER()

      RETURN
      END     ! SNANA_NEARNBR_APPLY_END


C =======================================
CDECK  ID>,  INIT_SNCID_LISTS. 
      SUBROUTINE INIT_SNCID_LISTS()

c Created Jun 9 2021
c Check CID lists from:
c   + integer list in NML (use and ignore)
c   + char list in NML    (use and ignore)
c   + list in separate file
c
c For string lists that can be very long (from list file),
c use match_cidlist_init[exec] utility in sntools.c[h];
c this match utility uses hash table for faster access.

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER i, LENF, LENC, NCCID_TMP, NCCID_FILE, OPTMASK
      CHARACTER FNAM*20, cFILE*(MXCHAR_FILENAME)
      CHARACTER CCID*(MXCHAR_CCID), cCCID*(MXCHAR_CCID)
      CHARACTER cBLANK*4, cVARLIST_STORE*60
      LOGICAL IS_CCID_LIST, IS_CIDINT_LIST, IS_FILE

      LOGICAL  VALIDFILENAME
      INTEGER  MATCH_CIDLIST_INIT, PARSE_NML_STRINGLIST
      EXTERNAL MATCH_CIDLIST_INIT

C ----------- BEGIN ------------

      IF ( SNCID_LIST_FILE(1:20) .EQ. 'HEADER_OVERRIDE_FILE' ) THEN
          SNCID_LIST_FILE = HEADER_OVERRIDE_FILE
      ENDIF

      cBLANK = ""//char(0)

      LENF    = INDEX(SNCID_LIST_FILE,' ') - 1
      cFILE   = SNCID_LIST_FILE(1:LENF) // char(0)

      IS_FILE = VALIDFILENAME(SNCID_LIST_FILE)

      NCID_LIST = 0; NCCID_LIST = 0; NCCID_FILE = 0

c check input methods to specify list of CID strings
      IS_CCID_LIST =
     &   ( SNCCID_LIST(1) .NE. ' ' )  .or.  ! char strings in NML
     &   ( IS_FILE )                        ! separate file list

      IS_CIDINT_LIST = SNCID_LIST(1) > 0

c - - - - - - -

      FNAM    = 'INIT_SNCID_LISTS'
      CALL PRBANNER(FNAM)

      IF ( IS_CIDINT_LIST .or. IS_CCID_LIST ) THEN
         CUTWIN_CID(1) = 0;  CUTWIN_CID(2) = 0
      ENDIF

c      print*,' xxx IS_CID/FILE/INT = ',
c     &    IS_CCID_LIST, IS_FILE, IS_CIDINT_LIST

c - - - - - - -
c check integer lists the old way
      IF ( IS_CIDINT_LIST ) THEN
         i = 1
         DO WHILE ( SNCID_LIST(i) .GE. 1 )
            i = i + 1
         END DO
         NCID_LIST = i - 1
         write(6,21) NCID_LIST
 21      format(T5,'Store ',I6,' integer CIDs from SNCID_LIST')
      ENDIF

      OPTMASK = 0

      IF ( IS_CCID_LIST ) THEN
         NCCID_TMP = MATCH_CIDLIST_INIT(cBLANK,OPTMASK,cBLANK, 4,4)

c  check SNCCID_LIST in &SNLCINP ...
         i = 1; CCID = SNCCID_LIST(i)
         DO WHILE( CCID .NE. ' ' )
            CALL NMLCHECK_SNCCID("SNCCID_LIST",CCID)
            LENC = INDEX(CCID,' ') - 1
            cCCID = CCID(1:LENC) // char(0)
            NCCID_TMP = MATCH_CIDLIST_INIT(cCCID,OPTMASK,cBLANK,LENC,4)
            i = i + 1 ; CCID = SNCCID_LIST(i)
         END DO
         NCCID_LIST = i - 1

c check CIDs from separate file (table format, or unformatted)
         IF ( IS_FILE ) THEN
            if ( NFIT_ITERATION > 0 ) then
           ! store SALT2 fit pars for INIVAL in snlc_fit evt sync
              cVARLIST_STORE = 'zHD,PKMJD,x0,x1,c' // char(0)
            else
              cVARLIST_STORE = cBLANK
            endif
            OPTMASK = 8 ! send reset for AUTOSTORE
            NCCID_FILE =
     &        MATCH_CIDLIST_INIT(cFILE,OPTMASK,cVARLIST_STORE, LENF,20)
         ENDIF

         write(6,31) NCCID_LIST, 'SNCCID_LIST'
         write(6,31) NCCID_FILE, 'SNCID_LIST_FILE'
 31      format(T5,'Store ',I6,  ' string  CIDs from ', A)

      ENDIF   ! end IS_CCID_LIST

      CALL FLUSH(6)

c - - - - - -
c Check ignore lists, and use brute-force matching since
c these lists should be small.

      i = 1 ; NCID_IGNORE=0
      DO WHILE ( SNCID_IGNORE(i) .GE. 1 )
         i = i + 1
      END DO
      NCID_IGNORE = i - 1

      i = 1
      DO WHILE ( SNCCID_IGNORE(i) .NE. ' ' )
         CALL NMLCHECK_SNCCID("SNCCID_IGNORE",SNCCID_IGNORE(i))
         i = i + 1
         SNCCID_IGNORE_ALL(i) = SNCCID_IGNORE(i)
      END DO
      NCCID_IGNORE = i - 1

c - - - -
      CALL  RDSNIGNORE          ! read IGNORE-list from user file
      NCCID_PLOT = PARSE_NML_STRINGLIST(SNCCID_PLOT,MXCHAR_CCID)

      if ( NCID_IGNORE > 0 .or. NCCID_IGNORE>0 ) then
         write(6,61) NCID_IGNORE,  'SNCID_IGNORE'
         write(6,61) NCCID_IGNORE, 'SNCCID_IGNORE'
 61      format(T5,'IGNORE ',I4,  ' CIDs from ', A)
      endif

c      print*,' xxx DEBUG STOP xxx'
c      STOP ! xxxx

      CALL FLUSH(6)


      RETURN
      END   ! end INIT_SNCID_LISTS


C =======================================
CDECK  ID>,  RD_SNMJDLIST. 
      SUBROUTINE RDFILE_SNMJDLIST
c
c Created May 2008 by R.Kessler
c
c Read list of "SNID MJD" to process SNID list,
c so that fitter can interpolate flux at MJD.
c Initial use is for Ryan Foley's analysis with
c KECK spectra for SDSS-discovered SN.
c Second usage is comparing CSP-vs-SDSS photometry (J.Mosher)
c
c May 28, 2008:
c   add screen-dump to see what's going on.
c
c Jan 2012:
c   check 'ALL' option to interpolate ALL SN at a MJD
c   After SN are read, a call to UPDSNMJDLIST checks the
c   ALL option.
c
c May 18, 2012: complete re-write

c ---------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


      INTEGER   iwd, NWD, LEN, N, j, LL0, LL1
      CHARACTER CCID*(MXCHAR_CCID), NAME_forC*(MXCHAR_FILENAME)
      CHARACTER CTMP0*40, CTMP1*40, FNAM*18
      REAL*8  MJD8
      LOGICAL LOK

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

c ---------- BEGIN ----------

      N_INTERP_MJDLIST    = 0


      IF ( SNMJD_LIST_FILE .EQ. ' ' ) RETURN

      FNAM = 'RDFILE_SNMJDLIST'
      N_INTERP_MJDLIST_DONE = 0
c init arrays
      N_INTERP_MJDLIST       = 0
      DO j = 1, MXINTERP
         INTERP8_MJDLIST(j)  = 0.0
         INTERP_CCIDLIST(j)  = ''
         INTERP_MJDLIST_DONE(j) = .FALSE.
      ENDDO

      CALL PRBANNER(FNAM)

      LEN = INDEX(SNMJD_LIST_FILE,' ') - 1
      print*,' '
      print*,'  Read flux-interpolation instructions from '
      print*,'  ', SNMJD_LIST_FILE(1:LEN)


      NAME_ForC = SNMJD_LIST_FILE(1:LEN)//char(0)
      NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_FILE, NAME_forC,
     &         FNAM//char(0), LEN, 18 )

      DO 100 iwd = 1, NWD-1, 2

         CALL get_PARSE_WORD_fortran(iwd+0, CTMP0, LL0 )
         CALL get_PARSE_WORD_fortran(iwd+1, CTMP1, LL1 )

         READ ( CTMP0, *) CCID
         READ ( CTMP1, *) MJD8

         N_INTERP_MJDLIST  = N_INTERP_MJDLIST + 1
         N = N_INTERP_MJDLIST

         INTERP_CCIDLIST(N) = CCID
         INTERP8_MJDLIST(N) = MJD8

         LEN = INDEX(CCID,' ') - 1
         write(6,70) CCID, MJD8
70       format(T6,'Will interpolate flux for SN ', A12,
     &        ' at MJD=', F10.3)

c --- error checking

         LOK = ( MJD8 .EQ. 0.0) .or.
     &         ( MJD8 .GT. 40000. .and. MJD8 .LT. 70000. )
         if ( .NOT. LOK ) then
            write(c1err,61) MJD8
61          format('Read Invalid MJD = ', F12.3,' from ' )
            c2err = SNMJD_LIST_FILE(1:80)
            CALL  MADABORT(FNAM, C1ERR, C2ERR)
         endif

c abort if we exceed array bound
         IF ( N_INTERP_MJDLIST .GT. MXINTERP ) THEN
            CALL PRINT_PREABORT_BANNER("RDFILE_SNMJDLIST"//char(0),40)
            print*,'   SNMJD_LIST_FILE = ', SNMJD_LIST_FILE
            write(c1err,161) CCID, MJD8
161         format('N_INTERP_MJDLIST exceeds bound at CID=',A8, 2x,
     &          'MJD=',F9.3)
            write(c2err,162) MXINTERP
162         format('Check MXINTERP=',I5,' and SNMJD_LIST_FILE above.')

           CALL  MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

100   CONTINUE  ! iwd

      RETURN
      END   ! end of RDFILE_SNMJDLIST

C =============================
CDECK  ID>,  GTINTLIST. 
      SUBROUTINE GET_INTERP_MJDLIST(CCID, NMJD, MJDLIST, ADDFLAG)
c
c Return NMJD and MJDLIST to interpolate for this CID.
c ADDFLAG = T if this CCID is specifically listed;
c ADDFLAG = F if this CCID is added because of the ALL option.
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


c subroutine args
      CHARACTER CCID*(*)  ! (I) SN character id
      INTEGER NMJD        ! (O) number of MJDs to interpolate
      LOGICAL ADDFLAG     ! (O) T => add to process list
      REAL*8
     &   MJDLIST(MXINTERP) ! (O) list of MJDs

c local var

      LOGICAL LMATCH, LALL
      INTEGER i, L0, L1
      character CCID_tmp*(MXCHAR_CCID)

c --------------- BEGIN --------------

      NMJD    = 0
      ADDFLAG = .FALSE.

      L0   = INDEX(CCID,' ') - 1

      DO 100 i = 1, N_INTERP_MJDLIST
         CCID_tmp = INTERP_CCIDLIST(i)
         L1 = INDEX(CCID_tmp,' ') - 1

         LMATCH = ( L0 .EQ. L1 ) .and.
     &            ( CCID(1:L0) .EQ. CCID_tmp(1:L1) )
         LALL    = CCID_tmp(1:3) .EQ. 'ALL'

         IF ( LMATCH ) ADDFLAG = .TRUE.  ! set return arg

c         print*,' xxx compare ', CCID,'  to ', CCID_tmp,
c     &     '  L0,L1=',L0,L1

         if ( LALL .or. LMATCH )then
           NMJD = NMJD + 1
           MJDLIST(NMJD) = INTERP8_MJDLIST(i)

c keep track of which ones are DONE to help know when to quit reading
           if ( .not. INTERP_MJDLIST_DONE(i) ) then
              N_INTERP_MJDLIST_DONE  = N_INTERP_MJDLIST_DONE + 1
              INTERP_MJDLIST_DONE(i) = .TRUE.
           endif

         endif
100   CONTINUE

      RETURN
      END

C =========================================
CDECK  ID>,  ENVreplace. 
      SUBROUTINE ENVreplace(STRING)

c If input STRING starts with '$' then evaluate ENV
c with GETENV and return STRING with substitution.
c
c There is a C version of this function in sntools.c,
c but passing back the return string to fortran is not
c so easy, so safer to write this one in fortran too.

      IMPLICIT NONE
      CHARACTER STRING*(*)  ! I/O

c local args

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



      INTEGER jslash, LTOT, LENV, LENS
      CHARACTER ENVname*200, ENV*400, SUFFIX*400
      CHARACTER C1ERR*72, C2ERR*72
      CHARACTER FNAM*12

C -------------- BEGIN -------------

      IF ( STRING(1:1) .NE. '$' ) RETURN

      FNAM = 'ENVreplace'

      LTOT    = INDEX(STRING,' ' ) - 1
      IF (LTOT <= 0 ) THEN
        CALL PRINT_PREABORT_BANNER(FNAM(1:10)//char(0), 40)
        print*,' STRING=', STRING
        write(c1err,31) LTOT
        c2err = 'STRING could be too long or zero length'
31      format( 'LEN(STRING)=', I3, ' ???' )
        CALL MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

      JSLASH  = INDEX(STRING,'/') - 1
      IF ( JSLASH <= 0 ) JSLASH = LTOT
      SUFFIX  = STRING(JSLASH+1:LTOT)
      LENS    = INDEX(SUFFIX,' ') - 1

      ENVname = STRING(2:JSLASH)
      CALL GETENV(ENVname, ENV) ! return ENV
      LENV    = INDEX(ENV,' ')-1

      if ( LENV > MXCHAR_PATH ) then
         write(C1ERR,61) ENVname(1:JSLASH-1), LENV
61       format('LEN($', A, ') = ',I3,' is too long.')
         write(C2ERR,62) MXCHAR_PATH
62       format('MXCHAR_PATH = ', I3 )
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

      if ( LENV+LENS > MXCHAR_FILENAME ) then
         write(C1ERR,161) STRING(1:LTOT), LENV+LENS
161       format('Decoded LEN($', A, ') = ',I3,' is too long.')
         write(C2ERR,162) MXCHAR_FILENAME
162       format('MXCHAR_FILENAME = ', I3 )
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

      if ( LENV .EQ. 0 ) then
         C1ERR = 'ENV = $' // ENVname(1:JSLASH) // ' is not defined.'
         C2ERR = 'Check your input namelists.'
         CALL MADABORT(FNAM, C1ERR, C2ERR)
      endif

      STRING = ENV(1:LENV) // SUFFIX

      RETURN
      END     ! end of ENVreplace

C ==============================
CDECK  ID>,  IGNOREFILE_fortran. 
      LOGICAL FUNCTION IGNOREFILE_fortran(fileName)

c Created Apri 2022
c Wrapper to call IGNOREFILE C-utility to return True if
c file = 'NULL' or 'NONE' or 'BLANK' or ''


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


      CHARACTER FILENAME*(*), cFILE*(MXCHAR_FILENAME)
      INTEGER LENF, IGNORE

      INTEGER  IGNOREFILE
      EXTERNAL IGNOREFILE
C --------- BEGIN -------------

      LENF = INDEX(FILENAME//' ',' ') - 1
      cFILE = FILENAME(1:LENF) // char(0)
      IGNORE = IGNOREFILE(cFILE,LENF)

c xxxxxxxx
c      print*,' xxx ------------------------------- '
c      print*,' xxx FILENAME = ', FILENAME(1:LENF)
c      print*,' xxx LENF = ', LENF
c      print*,' xxx IGNORE = ', IGNORE
c xxxxxxxxxx

      IGNOREFILE_fortran = (IGNORE .NE. 0 )

      RETURN
      END  ! end of IGNOREFILE_fortran

CDECK  ID>,  VALIDFILENAME. 
      LOGICAL FUNCTION VALIDFILENAME(fileName)
      CHARACTER FILENAME*(*)
      LOGICAL   IGNOREFILE_fortran
      VALIDFILENAME = ( .NOT. IGNOREFILE_fortran(FILENAME) )
      RETURN
      END

C =======================================
CDECK  ID>,  get_PARSE_WORD_fortran. 
      SUBROUTINE get_PARSE_WORD_fortran(iwd,WORD,LEN)
c
c Jan 2018
c Wrapper to call C-function get_PARSE_WORD to retrieve
c iwd word stored.
c
c Jan 2019: use MXCHAR_FILEWORD for char array abound.
c Jul 2020: extend WORD_C size to 4*MXCHAR_FILENAME
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



c subroutine args
      INTEGER   IWD           ! (I) word index to fetch
      CHARACTER WORD*(*)      ! (O) stored word
      INTEGER   LEN           ! (O) length of word

c local args
      INTEGER  iwd_C
      CHARACTER WORD_C*(4*MXCHAR_FILENAME)
      EXTERNAL GET_PARSE_WORD

C ------------- BEGIN -----------
      iwd_C = iwd-1
      CALL GET_PARSE_WORD(ONE, iwd_C, WORD_C, LEN)
      LEN  = INDEX(WORD_C, ' ' ) - 1
      WORD = WORD_C(1:LEN)
      RETURN
      END


C ======================
CDECK  ID>,  UPCASE. 
      SUBROUTINE UPCASE(strin, strupper)
      character strin*(*), strupper*(*)
      integer  j, LL

      strupper = ''
      LL = INDEX(strin,' ') - 1
      do j = 1, LL
       if(strin(j:j) >= "a" .and. strin(j:j) <= "z") then
         strupper(j:j) = achar(iachar(strin(j:j)) - 32)
       else
         strupper(j:j) = strin(j:j)
       end if
      end do
      END

C ======================
CDECK  ID>,  LOCASE. 
      SUBROUTINE LOCASE(strin, strlower)
c return strlower.
      character strin*(*), strlower*(*)
      integer  j, LL

      strlower = ''
      LL = INDEX(strin,' ') - 1
      do j = 1, LL
       if(strin(j:j) >= "A" .and. strin(j:j) <= "Z") then
         strlower(j:j) = achar(iachar(strin(j:j)) + 32)
       else
         strlower(j:j) = strin(j:j)
       end if
      end do
      END

C ===========================================
CDECK  ID>,  RDNINT. 
      SUBROUTINE RDNINT( cwords, NINT, IARRAY )
      IMPLICIT NONE
c ---------------------------------------------------
c Read NINT consecutive integers from cwords array
c Store results in IARRAY.
c --------------------------------------------------
      INTEGER   NINT
      character cwords(NINT)*60  ! (I) list of char words
      INTEGER   IARRAY(NINT)     ! (O) array of parsed integers
c local args
      INTEGER i
C ------------ BEGIN -----------
      DO i = 1, NINT
          read ( cwords(i), * ) IARRAY(i)
      ENDDO
      RETURN
      END

C ===========================================
CDECK  ID>,  RDNFLOAT. 
      SUBROUTINE RDNFLOAT ( CWORDS, NFLOAT, FARRAY )
      IMPLICIT NONE
c ---------------------------------------------------
c Read NFLOAT consecutive floats from CWORDS array
c Store results in FARRAY.
c
c Jul 2008: ABORT on 'nan'.
c Sep 2010: increase cwords bytes from 40 to 60
c
c --------------------------------------------------
      INTEGER NFLOAT
      character cwords(NFLOAT)*60  ! (I) list of char words
      REAL      FARRAY(NFLOAT)     ! (O) array of parsed floats
c local args
      INTEGER i
      character c1err*60, c2err*60
C ------------ BEGIN -----------
      DO i = 1, NFLOAT
          if ( cwords(i) .EQ. 'nan' ) then
             print*,' '
             c1err = "Found 'nan' instead of float. "
             c2err = "Use grep to find the nan in this version. "
             CALL MADABORT("RDNFLOAT", c1err, c2err )
          endif
          read ( cwords(i), * ) FARRAY(i)

      ENDDO
      RETURN
      END

C ===========================================
CDECK  ID>,  RDNDBLE. 
      SUBROUTINE RDNDBLE ( CWORDS, NDBLE, DARRAY )
      IMPLICIT NONE
c ---------------------------------------------------
c Created Jun 20, 2011
c Read NDBLE consecutive doubles from CWORDS array
c Store results in DARRAY.
c
c --------------------------------------------------
      INTEGER NDBLE
      character cwords(NDBLE)*60  ! (I) list of char words
      REAL*8    DARRAY(NDBLE)     ! (O) array of parsed floats
c local args
      INTEGER i
      character c1err*60, c2err*60
C ------------ BEGIN -----------
      DO i = 1, NDBLE
          if ( cwords(i) .EQ. 'nan' ) then
             print*,' '
             c1err = "Found 'nan' instead of dble. "
             c2err = "Use grep to find the nan in this version. "
             CALL MADABORT("RDNDBLE", c1err, c2err )
          endif
          read ( cwords(i), * ) DARRAY(i)
cc          read ( cwords(i), "(D20.10)" ) DARRAY(i)
      ENDDO
      RETURN
      END

C ==============================================
CDECK  ID>,  RDSTRING. 
      CHARACTER*80 FUNCTION RDSTRING( OPT, FILE )
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c Read single-word STRING from FILE
c OPT=0 => read from file
c OPT=1 => read from $SNDATA_ROOT/file

      INTEGER OPT
      CHARACTER FILE*(*)

c local var

      INTEGER LL
      CHARACTER LOCFILE*(MXCHAR_FILENAME), string*80

C -----------

      IF ( OPT .EQ. 0 ) THEN
         LOCFILE = FILE
      ELSE
         LL = INDEX(SNDATA_ROOT,' ') - 1
         LOCFILE = SNDATA_ROOT(1:LL) // '/' // FILE
      ENDIF

      OPEN (UNIT=LUNTMP, FILE = LOCFILE, STATUS='OLD', ERR=666 )
      READ(LUNTMP,*) string
      CLOSE ( UNIT = LUNTMP )

      RDSTRING = STRING
      RETURN

c --------------------
666   CONTINUE
      LL = INDEX(FILE,' ') - 1
      C1ERR = 'Cannot open file: ' // file(1:LL)
      CALL MADABORT("RDSTRING", C1ERR, "")

      RETURN
      END



C ================================================
CDECK  ID>,  INITSURVEY. 
      SUBROUTINE INIT_SURVEY(NSN_VERS)
c
c Created Jun 2011
c [re-named from RDSURVEY, and read-part moved to RDSURVEY_TEXT]
c
c Process a few things from the global survey variables
c read from RDSURVEY_TEXT[FITS]
c
c May 26, 2012: remove BX check; moved to LANDOLT_PREP.
c
c Jun 15, 2013: check FILTER_REPLACE option
c
c Aug 08, 2013: read and fill SURVEY_FIELD(i) for each survey field;
c               needed to sort overlapping fields so that
c               E2+E1 gets written as E1+E2
c
c Dec 16 2014: fix string logic checking SURVEY; see L1.
c
c Dec 09 2020: fix index bug setting SURVEY_TMP
c -------------

      IMPLICIT NONE

c subroutine args

      INTEGER NSN_VERS

c local variables.


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER
     &   iwd, NWD, IFILT_OBS, LL, L1, L2, LNAM,  i, IDTMP
     &  ,IDFIELD, NFILT_NONSURVEY, NFILT_ADD, iadd, jtmp
     &  ,LWD0, LWD1, LWD2, LWD3

      character
     &   FNAM*12, cwd*60, cwd_next*60, cwd_next2*60, cwd_next3*60
     &  ,cfilt1*2, SURVEY_TMP*(MXCHAR_SURVEY)
     &  ,SURVEYFILE*(MXCHAR_FILENAME)
     &  ,NAME_forC*(MXCHAR_FILENAME)
     &  ,upper*60, ctel*60, cfield*60
     &  ,SURVEY_FILTERS_ORIG*(MXFILT_ALL)

      LOGICAL LTMP, LKEY, LSRVY

c functions
      INTEGER FILTINDX
      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------------- BEGIN --------------

      FNAM            = 'INIT_SURVEY'
      IDSURVEY        = 0
      NFIELD_SURVEY   = 0
      NSURVEY_LIST    = 0

      LNAM  = INDEX ( SURVEY_NAME,    ' ' ) - 1
      L2    = 0

      IF ( FREEZE_SURVEY_FILTERS ) THEN
c        leave SURVEY_FILTERS and NFILTDEF_XXX alone
      ELSE
        L2  = INDEX ( SURVEY_FILTERS, ' ' ) - 1
        NFILTDEF_SURVEY = L2
        NFILTDEF_READ   = L2
      ENDIF

c ----------------------------------------
c Apr 2013: check user-option to add non-survey filters.
c           These extra filters must be defined in the kcor/calib file,
c           otherwise RDKCOR will abort.
c Jun 1 2013:
c  Only add NONSURVEY filter if it's NOT already defined. For example,
c  consider SDSS ugrizUGRIZ, but the simulations are done only with ugriz.
c  Thus we can define NONSURVEY_FILTERS ='UGRIZ' which are added to the
c  simulation list to avoid a KCOR-abort, but for data these NONSURVEY_FILTERS
c  are ignored since they are already defined.

      NFILT_NONSURVEY = INDEX(NONSURVEY_FILTERS,' ') - 1
      SURVEY_FILTERS_ORIG = SURVEY_FILTERS
      NFILT_ADD = 0
      NONSURVEY_FILTERS_ADD = ''

      DO 601 iadd = 1, NFILT_NONSURVEY
        cfilt1 = NONSURVEY_FILTERS(iadd:iadd)
        jtmp   = INDEX(SURVEY_FILTERS_ORIG,cfilt1(1:1))

        if ( jtmp .LE. 0 ) then
           NFILT_ADD = NFILT_ADD + 1
           NONSURVEY_FILTERS_ADD =
     &     NONSURVEY_FILTERS_ADD(1:NFILT_ADD-1) // cfilt1(1:1)
        endif

601   CONTINUE

      IF ( NFILT_ADD > 0 ) THEN
           NONSURVEY_FILTERS_ADD =
     &     NONSURVEY_FILTERS_ADD(1:NFILT_ADD) // '  '  ! add padding

         print*,'   Add NON-SURVEY FILTERS = ',
     &              NONSURVEY_FILTERS_ADD(1:NFILT_ADD)
         call flush(6)
         SURVEY_FILTERS  = SURVEY_FILTERS(1:NFILTDEF_SURVEY) //
     &                     NONSURVEY_FILTERS_ADD(1:NFILT_ADD)
         NFILTDEF_SURVEY = NFILTDEF_SURVEY + NFILT_ADD
         L2 = NFILTDEF_SURVEY
      ENDIF

c ----------------------------------------
c create IFILTDEF_MAP_SURVEY

       do i = 1, NFILTDEF_SURVEY
          cfilt1    = SURVEY_FILTERS(i:i)
          IFILT_OBS = FILTINDX(cfilt1)

          IFILTDEF_MAP_SURVEY(i)    = IFILT_OBS
          IFILTDEF_INVMAP_SURVEY(ifilt_obs) = i

          if ( IFILT_OBS .LE. 0 ) then
            CALL PRINT_PREABORT_BANNER("INIT_SURVEY"//char(0),40)
            print*,'   i = ', i,' of NFILTDEF_SURVEY=', NFILTDEF_SURVEY
            print*,'   IFILT_OBS = ', IFILT_OBS
            print*,'   CFILT1    = ', cfilt1

            c1err = 'FILTER = ' // cfilt1 //
     &         ' is invalid for SURVEY=' // SURVEY_NAME(1:LNAM)
            c2err = 'SURVEY_FILTERS = |' //
     &              SURVEY_FILTERS(1:NFILTDEF_SURVEY) // '|'
            CALL MADABORT(FNAM, c1err, c2err )
          endif

       enddo

c ------------
c Now open SURVEY.DEF file to get
c  IDSURVEY
c  IDFIELD

      LL = INDEX ( SNDATA_ROOT , ' ' ) - 1
      SURVEYFILE = SNDATA_ROOT(1:LL) // '/SURVEY.DEF'

      LL        = INDEX(SURVEYFILE,' ')-1
      NAME_forC = SURVEYFILE(1:LL)//char(0)
      NWD  = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_FILE, NAME_forC,
     &           FNAM//char(0), LL, 12)

      DO 110 iwd = 1, NWD-3

         CALL get_PARSE_WORD_fortran(iwd+0, cwd,       LWD0 )
         CALL get_PARSE_WORD_fortran(iwd+1, cwd_next,  LWD1 )
         CALL get_PARSE_WORD_fortran(iwd+2, cwd_next2, LWD2 )
         CALL get_PARSE_WORD_fortran(iwd+3, cwd_next3, LWD3 )
         if ( cwd .EQ. ' ' ) goto 110

         if ( cwd(1:7) .EQ. 'SURVEY:' ) then
            L1 = index(cwd_next,' ') - 1
            SURVEY_TMP  = cwd_next(1:L1)
            read(cwd_next2,*) IDTMP

c    store all survey names in case there are subSurveys
c    such as LOWZ(CFA3)
            NSURVEY_LIST = NSURVEY_LIST + 1
            SURVEY_NAME_LIST(NSURVEY_LIST) = SURVEY_TMP
            IDSURVEY_LIST(NSURVEY_LIST)    = IDTMP

            if ( SURVEY_TMP(1:L1) .EQ. SURVEY_NAME(1:LNAM) ) then
c     IDSURVEY should never change, but IDSUBSURVEY can change
               IDSURVEY=IDTMP ; IDSUBSURVEY=IDTMP
            endif
         endif

c ------------
c check SN field

         LKEY   = cwd .EQ. 'FIELD:'
         LSRVY  = .FALSE.
         IF ( LKEY ) THEN
            read(cwd_next3,*) SURVEY_TMP
            LSRVY  = SURVEY_TMP .EQ. SURVEY_NAME ! field for this survey
         ENDIF

         if ( LKEY .and. LSRVY ) then

          call UPCASE(cwd_next, upper)
          cfield = upper  ! FIELD in SURVEY.DEF file

          read(cwd_next2,*) IDFIELD

          IF ( IDFIELD > 0 ) THEN
             NFIELD_SURVEY = NFIELD_SURVEY + 1
             SURVEY_FIELDNAME(NFIELD_SURVEY)=cfield(1:MXCHAR_FIELDNAME)
             SURVEY_IDFIELD(NFIELD_SURVEY)  = IDFIELD
          ENDIF

          IF ( NFIELD_SURVEY > MXIDFIELD ) THEN
             write(c1err,681) MXIDFIELD
 681         format('NSURVEY_FIELD exceeds bound of ', I4)
             c2err = 'Check MXIDFIELD and SURVEY.DEF file.'
             CALL MADABORT(FNAM, c1err, c2err )
          ENDIF

c now compare with user request, and convert everything to upper case

           DO i = 1, NIDFIELD_LIST
c convert user name to uppercase
             CALL UPCASE(SNFIELD_LIST(i), upper)
             SNFIELD_LIST(i) = upper   ! user-specified field
             LL = INDEX( cfield, ' ' ) - 1

             if ( cfield(1:LL) .EQ. SNFIELD_LIST(i)(1:LL) ) then
               SNFIELD_LIST(i) = cfield  ! truncate extra characters
               IDFIELD_LIST(i) = IDFIELD
               write(6,206) CFIELD(1:LL), IDFIELD
206            format(T5,'Found requested FIELD=',A,2x,
     &               'with IDFIELD=', I3 )
             endif
            END DO

         endif  ! end of FIELD: if-block

110   CONTINUE

c ------------------------
c print some info to stdout

      IF ( IDSURVEY .LE. 0 .and. SUBSURVEY_NAME .EQ. '' ) then
        c1err = 'Could not find IDSURVEY for SURVEY='
     &        // SURVEY_NAME(1:LNAM)
        c2err = 'Check ' // SURVEYFILE(1:72)
        CALL MADABORT(FNAM, c1err, c2err )
      endif

      if ( DO_GETINFO ) return ! Apr 2021

      write(6,201) SURVEY_NAME(1:LNAM), IDSURVEY
201   format(T5,'Found SURVEY  = ',A, 3x, '(IDSURVEY=',I3,')' )

      write(6,202) SURVEY_FILTERS(1:L2), NFILTDEF_SURVEY
202   format(T5,'Found FILTERS = ',A, 3x, '(NFILTDEF=',I3,')' )

      write(6,204) NSN_VERS
204   format(T5,'Found ',I7,' SN Candidates to Process.')

      print*,' '
      call flush(6)

c --------------------------------------------------------

      IF ( .NOT. DOALL_SNFIELD ) THEN
        DO i    = 1, NIDFIELD_LIST
          cfield  = SNFIELD_LIST(i)
          idfield = IDFIELD_LIST(i)
          if ( idfield .LT. 0 ) then
             LL = index( cfield, ' ' ) - 1
             c1err = 'Unknown FIELD: ' // cfield(1:LL)
             c2err = 'Check namelist variable SNFIELD_LIST '
             CALL MADABORT(FNAM, c1err, c2err )
          endif
        ENDDO
      ENDIF


c ---------------------------------
c check for FILTER_REPLACE option

      CALL INIT_FILTER_REPLACE()

c Apr 2021: check option to use survey name for TEXTFILE_PREFIX
      if ( TEXTFILE_PREFIX(1:6) == 'SURVEY' ) then
          TEXTFILE_PREFIX = SURVEY_NAME
      endif

      RETURN
      END      ! end of INIT_SURVEY

C ===================================
CDECK  ID>,  INIFLTREPLACE. 
      SUBROUTINE INIT_FILTER_REPLACE()

C Created Jun 2013 by R.K.
C Initialize IFILTOBS_REPLACE array based on user input
c string FILTER_REPLACE read from &SNLCINP namelist.
C After this init, can use FILTINDX_REPLACE function.
c
c Example:  FILTER_REPLACE = 'UGRIZ -> ugriz' will
c internally replace UGRIZ with ugriz so that we can
c analyze 'ugriz' (intead of ugrizUGRIZ) and get
c all of the epochs. This is intended for cases in
c which UGRIZ and ugriz bands are very similar.
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER
     &  IFILTOBS, NF1, NF2, NFARROW, IFILT, NWD, LF
     & ,IFILTOBS_ORIG

      CHARACTER
     &   ARROW*60
     &  ,FILTLIST1*(MXFILT_ALL)
     &  ,FILTLIST2*(MXFILT_ALL)
     &  ,NAME_forC*(MXFILT_ALL)
     &  ,FNAM*20
     &  ,CFILT_ORIG*2
     &  ,CFILT_REPLACE*2

c function
      INTEGER FILTINDX
      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------- BEGIN ------------

      NFILT_REPLACE = 0
      DO IFILTOBS = 1, MXFILT_ALL
        IFILTOBS_REPLACE(IFILTOBS) = IFILTOBS  ! default is 1-to-1 map
      ENDDO

      FNAM = 'INIT_FILTER_REPLACE'

      IF ( FILTER_REPLACE .NE. ' ' ) THEN

        LF        = INDEX(FILTER_REPLACE,' ', BACK=.TRUE.) - 1
        NAME_forC = FILTER_REPLACE(1:LF) // char(0)
        NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_STRING,NAME_forC,
     &             FNAM//char(0), LF, 20)

        CALL get_PARSE_WORD_fortran(1, FILTLIST1, NF1)
        CALL get_PARSE_WORD_fortran(2, ARROW,     NFARROW)
        CALL get_PARSE_WORD_fortran(3, FILTLIST2, NF2)

c idiot checks

        if ( NF1 .NE. NF2 ) THEN
           c1err = 'Cannot use FILTER_REPLACE with ' //
     &              'different size lists.'
           c2err = 'N(' // FILTLIST1(1:NF1) // ')' //
     &         ' != N(' // FILTLIST2(1:NF2) // ')'
           CALL MADABORT(FNAM, c1err, c2err )
        ENDIF
        IF ( ARROW(1:2) .NE. '->' ) THEN
           c1err = 'Second string of FILTER_REPLACE must by  ->'
           c2err = 'Check &SNLCINP namelist.'
           CALL MADABORT(FNAM, c1err, c2err )
        ENDIF

        NFILT_REPLACE = NF1
        DO IFILT = 1, NFILT_REPLACE
           CFILT_ORIG    = FILTLIST1(IFILT:IFILT)
           CFILT_REPLACE = FILTLIST2(IFILT:IFILT)

           IFILTOBS_ORIG                 = FILTINDX(CFILT_ORIG)
           IFILTOBS_REPLACE(IFILTOBS_ORIG) = FILTINDX(CFILT_REPLACE)

           write(6,20) CFILT_ORIG, CFILT_REPLACE, IFILTOBS_ORIG,
     &                    IFILTOBS_REPLACE(IFILTOBS_ORIG)
 20        format(T10,'FILTER_REPLACE:  ', A, ' -> ', A, 3x,
     &        '(',I3,' -> ', I3, ')' )
           CALL FLUSH(6)
        ENDDO
        print*,' '

c        print*,' xxx FILTLIST1 = ', FILTLIST1(1:12), NF1
c        print*,' xxx FILTLIST2 = ', FILTLIST2(1:12), NF2
c        print*,' xxx ARROW = ', ARROW
c        print*,' xxx REPLACE ', NFILT_REPLACE,'  filters '


      ENDIF

      RETURN
      END

C =============================
CDECK  ID>,  SETSURVEY. 
      SUBROUTINE SET_SURVEY(NAME, NFILTDEF, IFILTDEF, LAMSHIFT )
c
c May 18, 2008
c
c Set survey and IFILTDEF_[INV]MAP_SURVEY variables
c by passing them (i.e., from simulation) rather than
c by calling RDSURVEY.
c
c Jun 20 2017: pass LAMSHIFT as argument.
c
c ---------

      IMPLICIT NONE
c subroutine args

      CHARACTER NAME*(*)         ! (I) name of survey

      INTEGER
     &    NFILTDEF            ! (I) number of survey filters
     &   ,IFILTDEF(NFILTDEF)  ! (I) absolute filter indices

      REAL LAMSHIFT(NFILTDEF) ! (I) LAMSHIFT for each band

c local args


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER ifilt, ifilt_obs

c ---------------- BEGIN ------------

      SURVEY_NAME     = NAME
      NFILTDEF_SURVEY = NFILTDEF


      DO ifilt    = 1, NFILTDEF
        ifilt_obs = IFILTDEF(ifilt)
        IFILTDEF_MAP_SURVEY(ifilt)        = ifilt_obs
        IFILTDEF_INVMAP_SURVEY(ifilt_obs) = ifilt
        FILTER_LAMSHIFT_FILT(ifilt_obs)   = LAMSHIFT(IFILT)
      ENDDO


c Apr 2013: make sure to abort on bad kcor redshift.
      ABORT_ON_BADZ = .TRUE.

      RETURN
      END

C ================================================
CDECK  ID>,  ABTREST. 
      SUBROUTINE ABORT_ON_CUTWIN_TREST()

C Feb 2014
C Utility called by photo-z fitting program to abort
C if any of the SNANA-Trest cuts are set ... because
c for photo-z fit we cannot make an a-priori cut that
c depends on redsfhit. Try CUTWIN_TOBSMIN, CUTWIN_TOBSMAX,
c and other cuts that do NOT depend on the fitted photo-z.
c
c  To override this abort, set
c  &SNLCINP
c    ABORT_ON_TRESTCUT = F
c -------------------------------------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------


      INTEGER NCUT, i, icut, ICUTLIST(20)
      INTEGER NCUT_USE, LEN
      LOGICAL LLO, LHI
      REAL    VLO, VHI

      CHARACTER c1err*76, C2err*76

C --------------- BEGIN --------------
      NCUT = 0

      NCUT = NCUT + 1 ;   ICUTLIST(NCUT) = CUTBIT_TREST
      NCUT = NCUT + 1 ;   ICUTLIST(NCUT) = CUTBIT_TRESTMIN
      NCUT = NCUT + 1 ;   ICUTLIST(NCUT) = CUTBIT_TRESTMAX
      NCUT = NCUT + 1 ;   ICUTLIST(NCUT) = CUTBIT_TGAPMAX
      NCUT = NCUT + 1 ;   ICUTLIST(NCUT) = CUTBIT_T0GAPMAX

      NCUT_USE = 0
      Do 100 i = 1, NCUT
         icut  = ICUTLIST(i)
         VLO   = CUTWIN_VAR(1,icut)
         VHI   = CUTWIN_VAR(2,icut)

         LLO   = ( VLO > -.99*CUTVAL_OPEN )
         LHI   = ( VHI < +.99*CUTVAL_OPEN  )
         if ( LLO .or. LHI ) THEN
            NCUT_USE = NCUT_USE + 1
            LEN = INDEX(CUTVAR_NAME(icut),' ') - 1
            write(6,60) CUTVAR_NAME(icut), VLO, VHI
 60         format(T5,'WARNING: should not use CUTWIN_', A15,
     &            2x, F10.3,' - ', F10.3 )
            call flush(6)
         endif
 100  CONTINUE

      IF ( NCUT_USE > 0 .and. ABORT_ON_TRESTCUT ) THEN
         write(c1err,160) NCUT_USE
 160     format(I3,' Trest &SNLCINP cuts above are forbidden.' )
         c2err = 'Can override abort with &SNLCINP ABORT_ON_TRESTCUT=F'
         CALL MADABORT('ABORT_ON_CUTWIN_TREST', c1err, c2err )
      ENDIF

      RETURN
      END    ! end ABORT_ON_CUTWIN_TREST

C ================================================
CDECK  ID>,  RDEPIG. 
      SUBROUTINE READ_EPIGNORE_FILE ( IVERS  )
c
c Created May 6, 2008 by R.Kessler
c Read list of epochs to ignore.
c
c Use namelist variable EPOCH_IGNORE_FILE:
c if 'DEFAULT', then read [SNDATA_PREFIX].IGNORE.
c
c Fill variables in common EPXCOM
c
c File syntax is
c
c  IGNORE:  <CID1>  <MJD1>  <FILTER1>
c  IGNORE:  <CID2>  <MJD2>  <FILTER2>
c  etc ...
c
c  where <FILTER> is 'g' or 'r' or 'i' etc ...
c
c  and/or
c
c PHOTFLAG_MSKREJ:  <mask>  ! apply to PHOTFLAG
c    or
c PHOTFLAG_BITLIST_REJECT: 2,3,4  ! convert bits to mask
c
c PRIORITY for setting PHOTFLAG_MSKREJ
c   + user input via &SNLCINP -> top priority
c   + [VERSION].IGNORE file   -> next priority
c
c Strategy is that PHOTFLAG_MSKREJ is initialized to -1 before
c reading &SNLCINP ... which is before calling this function.
c If PHOTFLAG_MSKREJ >=0 here, then it picked up a value from &SNLCINP
c and it is NOT allowed to be modified here.
c If PHOTFLAG_MSKREJ < 0 here, then it can be updated by contents
c    of [VERSION].IGNORE file.
c
c Aug 27 2020: for externally supplied .IGNORE  file, make DOCANA check.
c Feb 06 2021: IGNORE file is now optional ! No longer required !
c May 13 2021: check for PHOTFLAG_MSKREJ in IGNORE file
c
c ----------------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &    IVERS        ! (I) use this version index

c local var

      INTEGER LL, LL1, LL2, LL3, LV, LF, BIT
      INTEGER iwd, NWD, N, LUN, NREAD_IGNORE
      LOGICAL LEXIST, FOUND_EPIGNORE, NOTSET
      REAL*8 MJD8
      CHARACTER
     &   LOCAL_FILENAME*(MXCHAR_FILENAME)
     &  ,NAME_forC*(MXCHAR_FILENAME)
     &  ,VERSION*(MXCHAR_VERSION)
     &  ,cwd*(MXCHAR_FILEWORD), cflt*4
     &  ,cwd_tmp*(MXCHAR_FILEWORD)
     &  ,ccid*(MXCHAR_CCID)
     &  ,ccid_last*(MXCHAR_CCID)
     &  ,STRING_BITLIST*60
     &  ,FNAM*30

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------- BEGIN ----------

      FNAM = 'READ_EPIGNORE_FILE'

      LUN = LUNTMP

      VERSION  = VERSION_PHOTOMETRY(ivers)
      LV       = index(VERSION,' ') - 1

      FOUND_EPIGNORE = .FALSE.
      STRING_BITLIST = ''

      CALL PRBANNER ( "READ_EPIGNORE_FILE:" )

      if ( EPOCH_IGNORE_FILE(1:4) .EQ. 'NONE' ) GOTO 8000
      if ( EPOCH_IGNORE_FILE(1:4) .EQ. 'NULL' ) GOTO 8000

c check if file is default, or if provided by user.

      IF ( EPOCH_IGNORE_FILE(1:7) .EQ. 'DEFAULT' ) THEN
        LL = INDEX( SNDATA_PREFIX, ' ' ) - 1
        LOCAL_FILENAME = SNDATA_PREFIX(1:LL) // '.IGNORE'

c       bail if default file does not exist (Feb 2021)
        inquire (file=LOCAL_FILENAME, exist=LEXIST)
        if ( .NOT. LEXIST ) THEN
           print*,'    Default IGNORE file does not exist -> skip read.'
           call flush(6)
           GOTO 8000
        endif
      ELSE
        LOCAL_FILENAME = EPOCH_IGNORE_FILE
      ENDIF

c for multiple versions, don't bother re-reading  the same
c IGNORE file
      IF ( IVERS > 1 ) then
        LF  = INDEX(LOCAL_FILENAME,' ') - 1
        IF ( LOCAL_FILENAME(1:LF) .EQ.
     &       EPOCH_IGNORE_LASTFILE(1:LF) ) THEN
             RETURN
        ENDIF
      ENDIF

c -----------
c Now start reading file

      LL = INDEX( LOCAL_FILENAME, ' ' ) - 1
      NAME_forC = LOCAL_FILENAME(1:LL)//char(0)

      NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_FILE, NAME_forC,
     &         FNAM//char(0), LL, 30)

      write(6,50) LOCAL_FILENAME(1:LL)
50    format(T5,'Read epochs to ignore from: ', /, T5, A)

      NREAD_IGNORE = 0
      CCID_LAST    = EPOCH_IGNORE_CCID(1)

      DO 200 iwd = 1, NWD

         CALL get_PARSE_WORD_fortran(iwd,cwd,LL)

         if ( cwd .EQ. 'IGNORE:' ) then

           NREAD_IGNORE = NREAD_IGNORE + 1
           CALL get_PARSE_WORD_fortran(iwd+1,CCID,LL1)
           if ( IVERS .GT. 1 .and. ccid .EQ. CCID_LAST ) then
             print*,'   IGNORE file already read -> SKIP re-reading. '
             return
           endif

           NEPOCH_IGNORE = NEPOCH_IGNORE + 1
           N = NEPOCH_IGNORE

           if ( N .GT. MXEPOCH_IGNORE ) then
              write(c1err,661) N
661           format('NEPOCH_IGNORE=',I4,' exceeds array bound.')
              c2err = 'Check file: ' // LOCAL_FILENAME(1:LL)
              CALL MADABORT("READ_EPIGNORE", c1err, c2err )
           endif

           CALL get_PARSE_WORD_fortran(iwd+2,CWD_TMP,LL2)
           read(cwd_tmp,*) MJD8

           CALL get_PARSE_WORD_fortran(iwd+3,CWD_TMP,LL3)
           cflt =  CWD_TMP(1:4)
           EPOCH_IGNORE_CCID(N)  = CCID
           EPOCH_IGNORE_FILT(N)  = cflt
           EPOCH_IGNORE_MJD(N)   = MJD8

           LL = INDEX(CCID,' ' ) - 1
           IF ( LL .LE. 0 ) LL = MXCHAR_CCID

c           write(6,55) N, CCID(1:LL), MJD8, cflt
c55         format(T4,I3,': Add ignore-epoch to list for CID=',A,
c     &         3x,'MJD=',F9.3, 2x,'FILT=',A)

         endif

c May 2021: check for PHOTFLAGs to reject epochs
         NOTSET = (PHOTFLAG_MSKREJ(1) < 0)
         if ( cwd .EQ. 'PHOTFLAG_MSKREJ:' .and. NOTSET ) then
            CALL get_PARSE_WORD_fortran(iwd+1,cwd_tmp,LL1)
            read(cwd_tmp,*) PHOTFLAG_MSKREJ(1)
         endif

         if ( cwd .EQ. 'PHOTFLAG_BITLIST_REJECT:' ) then
            CALL get_PARSE_WORD_fortran(iwd+1,STRING_BITLIST,LL1)
         endif

200   ENDDO

      EPOCH_IGNORE_LASTFILE = LOCAL_FILENAME
      call FLUSH(6)

C -------------------------------------------
8000  CONTINUE

c parse BITLIST after reading IGNORE file to avoid parse_WORD conflicts
      NOTSET = (PHOTFLAG_MSKREJ(1) < 0)
      IF ( STRING_BITLIST .NE. ' ' .and. NOTSET ) THEN
         PHOTFLAG_MSKREJ(1) = 0
         LL = INDEX(STRING_BITLIST,' ') - 1
         NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_STRING,
     &            STRING_BITLIST(1:LL)//char(0), FNAM//char(0), LL, 30)
         do iwd = 1, NWD
            CALL get_PARSE_WORD_fortran(iwd,cwd_tmp,LL1)
            read(cwd_tmp,*) BIT
            PHOTFLAG_BITLIST_REJECT(iwd) = BIT
            PHOTFLAG_MSKREJ(1) = IBSET(PHOTFLAG_MSKREJ(1),BIT)
         enddo
      ENDIF

c if PHOTFLAG_MSKREJ is still negative, then it has not been set;
c in this case, set it to zero so that it doesn't reject anything.
      IF ( PHOTFLAG_MSKREJ(1) < 0 ) PHOTFLAG_MSKREJ(1) = 0

      if ( NEPOCH_IGNORE > 0 ) then
         FOUND_EPIGNORE = .TRUE.
         write(6,801) NEPOCH_IGNORE
 801     format(T5,'EPOCH_IGNORE: Found ', I5,' epochs to IGNORE')
      endif

      if ( PHOTFLAG_MSKREJ(1) > 0 ) then
         write(6,802) PHOTFLAG_MSKREJ(1)
         FOUND_EPIGNORE = .TRUE.
 802     format(T5,'EPOCH_IGNORE: ignore epochs with PHOTFLAG & ', I8 )
      endif

      if ( .NOT. FOUND_EPIGNORE ) then
         print*,'   EPOCH_IGNORE: ' //
     &          'No epochs are ignored => use all epochs. '
      endif
      print*,' '

      CALL FLUSH(6)

      RETURN
      END  ! end of READ_EPIGNORE_FILE

C =============================
CDECK  ID>,  PASS_EPIGNORE_FILE. 
      LOGICAL FUNCTION PASS_EPIGNORE_FILE(EP)

c Created Feb 2021
c Returns True if this epoch (EP) is NOT listed in the
c epoch IGNORE file associated with VERSION.IGNORE,
c or with user input EPOCH_IGNORE_FILE.
c Note that cuts are NOT applied here; this function simply
c checks against an already existing list of epochs to ignore.
c

      IMPLICIT NONE

      INTEGER EP ! (I) epoch index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER  i, LL, ifilt_obs
      LOGICAL  LFILT, IGNORE, LMJD, LCID
      REAL*8    MJD8
      CHARACTER CFILT*2, CCID*(MXCHAR_CCID)

C --------------- BEGIN ----------

      IGNORE = .FALSE.

      DO 100 i = 1, NEPOCH_IGNORE

        CCID = SNLC_CCID
        LL   = ISNLC_LENCCID
        LCID = EPOCH_IGNORE_CCID(i)(1:LL) .EQ. CCID(1:LL)
        IF ( .NOT. LCID ) GOTO 100

c leave big margin for MJD check (.002 days) in case IGNORE
c file has round-off errors for the MJD.
        MJD8 = SNLC8_MJD(ep)
        LMJD = ( ABS(EPOCH_IGNORE_MJD(i)-MJD8) < 0.002 )
        IF ( .NOT. LMJD ) GOTO 100

        ifilt_obs = ISNLC_IFILT_OBS(ep)
        cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
        LFILT     = EPOCH_IGNORE_FILT(i)(1:1) .EQ. CFILT(1:1)
        IF ( .NOT. LFILT ) GOTO 100

c if we get here, then give message to ignore epoch
c and skip down to over-write part.

        IGNORE = .TRUE.

        IF ( STDOUT_UPDATE ) THEN
          write(6,101) CCID, MJD8, cfilt
        ENDIF
101     format(T8,'IGNORE EPOCH FOR: CID=',A8,
     &         3x,'MJD=',F9.3, 3x,'FILT=',A )

100   CONTINUE

      PASS_EPIGNORE_FILE = (.NOT. IGNORE)

      RETURN
      END    ! PASS_EPIGNORE_FILE

C ================================================
CDECK  ID>,  CHKFMT. 
      SUBROUTINE CHECK_FORMAT()

c Created Jun 15, 2011 by R.Kessler
c Check if format is FITS or TEXT;
c set global logical FORMAT_FITS or FORMAT_TEXT
c
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITSCOM. inserted below by ypatchy. 

c define external C functions to read from fits files

c max length of catenated strings from all epochs;
c e.g., FIELD
c Aug 31 2023: 40k -> 80k
c Nov 16 2023: 80k -> 160k

      INTEGER MXLEN_EPSTRING
      PARAMETER (MXLEN_EPSTRING = 160000 )

      INTEGER
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR  ! read string
     &  ,RD_SNFITSIO_INT  ! read int
     &  ,RD_SNFITSIO_SHT  ! read short int
     &  ,RD_SNFITSIO_FLT  ! read float
     &  ,RD_SNFITSIO_DBL  ! read double

      EXTERNAL
     &   RD_SNFITSIO_PREP
     &  ,RD_SNFITSIO_STR
     &  ,RD_SNFITSIO_INT
     &  ,RD_SNFITSIO_SHT
     &  ,RD_SNFITSIO_FLT
     &  ,RD_SNFITSIO_DBL
     &  ,SET_RDMASK_SNFITSIO ! void
     &  ,RD_SNFITSIO_CLOSE   ! void function

c Define index-lookup arrays used for faster reading of fits files
      INTEGER MXFITSPAR
      PARAMETER ( MXFITSPAR = 400 )

      INTEGER
     &   INDXFITS_HEAD(MXFITSPAR)    ! used in RDSNFITS_HEAD
     &  ,INDXFITS_EPCUTS(MXFITSPAR)  ! used in RDSNFITS_EPCUTS
     &  ,INDXFITS_PHOT(MXFITSPAR)    ! used in RDSNFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,SNFITSIO_CODE_IVERSION     ! FITSIO version used to write data

c defin epoch mask for which

      INTEGER
     &   EPOCH_RDMASK_SNFITSIO(MXEPOCH)  ! epochs to keep/reject

c define long fits-string returned by RD_SNFITSIO_STR
      CHARACTER STRFITS*(MXLEN_EPSTRING)

      COMMON / FITSCOM /  SNFITSIO_CODE_IVERSION
     &  ,INDXFITS_HEAD, INDXFITS_EPCUTS, INDXFITS_PHOT
     &  ,IPARFITS_HEAD
     &  ,EPOCH_RDMASK_SNFITSIO, STRFITS



      INTEGER    IVERS, OPT, ISTAT, LEN_VERS, LEN_PATH
      CHARACTER  VERSION*(MXCHAR_VERSION), PATH*(MXCHAR_PATH)

C ------------ BEGIN -----------

c check for subfolder; e.g., VERSION_PHOTOMETRY = 'JLA2014/JLA2014_CSP'
      CALL PREP_VERSION_SUBFOLDER()

c use first version on list since all versions must have same format
      IVERS    =  1
      VERSION  = VERSION_PHOTOMETRY(ivers)
      LEN_VERS = INDEX(VERSION,' ') - 1
      VERSION  = VERSION(1:LEN_VERS) // char(0)

      LEN_PATH = INDEX(PRIVATE_DATA_PATH,' ') - 1
      PATH     = PRIVATE_DATA_PATH(1:LEN_PATH) // char(0)

      OPT      = 1  ! option to check format and return
      ISTAT    = RD_SNFITSIO_PREP(OPT, PATH, VERSION,
     &     LEN_PATH, LEN_VERS)

      IF ( ISTAT .GT. 0 ) THEN
         FORMAT_FITS = .TRUE.
      ELSE
         FORMAT_TEXT = .TRUE.
      ENDIF

      RETURN
      END      ! end CHECK_FORMAT


C ================================================
CDECK  ID>,  SELEP_DRIVER. 
      SUBROUTINE SELECT_EPOCH_DRIVER(OPT)

c Created Feb 2021 (used by REFAC_READ_DATA)
c
c OPT += 1 -> Apply all epoch cuts except for Trest
c                 (e..g, before calling SET_PEAKMJD
c
c OPT += 2 -> Apply only Trest cut (e.g, after SET_PEAKMJD)
c
c OPT  = 3 -> apply all obs/epoch cuts

      IMPLICIT NONE

      INTEGER OPT  ! (I)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


      REAL*8    MJD8, MJD8_LAST
      INTEGER   NMJD_STORE_NEW, NMJD_STORE_ORIG, NEWMJD
      INTEGER   EPMIN, EPMAX, ep_orig, ep_new, IMJD
      INTEGER   IFILT, IFILT_OBS
      REAL      PEAKMJD, MJD, TOBS, TREST, z1, z
      LOGICAL   APPLY_CUTS, APPLY_TREST
      LOGICAL   PASS_CUTS, PASS_TREST, PASS
      CHARACTER FNAM*20

c function
      LOGICAL PASS_EPOCH_CUTS, PASS_EPOCH_TREST

c ------------------- BEGIN -------------------

      FNAM = 'SELECT_EPOCH_DRIVER'
      NMJD_STORE_NEW  = 0
      NMJD_STORE_ORIG = ISNLC_NEWMJD_STORE
      EP_NEW          = 0
      MJD8_LAST       = -9.0

      APPLY_CUTS  = BTEST(OPT,0)
      APPLY_TREST = BTEST(OPT,1)

      DO 101 NEWMJD = 1, ISNLC_NEWMJD_STORE
         EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
         EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

         PASS_CUTS  = .TRUE.
         PASS_TREST = .TRUE.

         if ( APPLY_CUTS ) then
            PASS_CUTS = PASS_EPOCH_CUTS(1,EPMIN)
         endif

         if ( APPLY_TREST ) then
            PEAKMJD = SNLC_SEARCH_PEAKMJD
            z       = SNLC_REDSHIFT
            PASS_TREST = PASS_EPOCH_TREST(z,PEAKMJD,EPMIN)
         endif

         PASS = PASS_CUTS .and. PASS_TREST

         if ( .NOT. PASS ) goto 101

         NMJD_STORE_NEW = NMJD_STORE_NEW + 1
         IMJD           = NMJD_STORE_NEW
         ISNLC_NFILT_NEWMJD(IMJD) = ISNLC_NFILT_NEWMJD(NEWMJD)

c overwrite EPOCH-dependent arrays to exclude rejected epochs

        DO 102 EP_ORIG = EPMIN, EPMAX

         EP_NEW = EP_NEW + 1

         MJD8  = SNLC8_MJD(EP_ORIG)
         if ( MJD8 > MJD8_LAST ) then
            if ( EP_ORIG == EPMIN ) then
              ISNLC_EPOCH_RANGE_NEWMJD(1,IMJD) = EP_NEW
            endif
              ISNLC_EPOCH_RANGE_NEWMJD(2,IMJD) = EP_NEW
         endif
         MJD8_LAST = MJD8

         if ( EP_NEW > EP_ORIG ) then
            CALL PRINT_PREABORT_BANNER(FNAM//char(0),40)
            print*,'    OPT = ', OPT
            print*,'    EPMIN, EPMAX = ', EPMIN, EPMAX
            print*,'    NEWMJD(ORIG,NEW) = ', NEWMJD, IMJD
            write(c1err,61) EP_NEW, EP_ORIG
61          format('Invalid EP_NEW=',I4, ' > EP_ORIG=',I4)
            c2err = 'Something is messed up.'
            CALL MADABORT(FNAM, c1err, c2err)
         endif

         CALL MOVE_SNLC_ARRAYS(EP_NEW,EP_ORIG)

102     CONTINUE
101     CONTINUE

      ISNLC_NEWMJD_STORE = NMJD_STORE_NEW

      RETURN
      END    ! end SELECT_EPOCH_DRIVER


C ===========================================
CDECK  ID>,  PASS_EP_CUTS. 
      LOGICAL FUNCTION PASS_EPOCH_CUTS(OPTMASK,EP)

C Created Feb 2021
C Return TRUE if epoch passes explicit epoch cuts such as
c PSF, PHOTFLAG, etc ..
c   (no implicit cuts such as TREST)
c
c Mar 25 2021: init BADPHOT=F (bug fix)
c -----------------

      IMPLICIT NONE

c input args
      INTEGER OPTMASK, EP  ! (I)

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


      INTEGER PHOTFLAG, OV, i, IFILT, IFILT_OBS, IDFIELD
      LOGICAL BADPHOT, REJECT, LXMJD, LTMP, NO_DETECT
      REAL    ZP, PSF, MJD, SNR
c functions
      LOGICAL PASS_EPIGNORE_FILE, SELECT_EARLYLC

C ----------- BEGIN ------------

      PASS_EPOCH_CUTS = .TRUE.  ! init return arg
      REJECT          = .FALSE.

      IFILT_OBS = ISNLC_IFILT_OBS(EP)
      IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
      IDFIELD   = ISNLC_IDFIELD(EP)
      PHOTFLAG  = ISNLC_PHOTFLAG(ep)
      ZP        = SNLC_ZEROPT_forCUT(ep)
      PSF       = SNLC_PSF_FWHM_ARCSEC(EP)
      MJD       = SNGL(SNLC8_MJD(ep))

c Jul 2020: check option to write list of rejected epochs

      if ( .NOT. PASS_EPIGNORE_FILE(EP) ) then
         PASS_EPOCH_CUTS = .FALSE.
         return
      endif

c ----------------------------------------------
c now check PHOTFLAG mask.

      BADPHOT = .FALSE.

c check OR-logic
c ==> reject epoch if any PHOTFLAG_MSKREJ bit is set
      OV   = IAND ( PHOTFLAG_MSKREJ(1), PHOTFLAG )
      IF ( OV > 0 ) THEN
         BADPHOT = .TRUE.  ;  REJECT  = .TRUE.
      ENDIF

c Now check AND logic
c ==> reject epoch if all PHOTFLAG_MSKREJ(2:5) bits are set

      do i = 2, 5
        OV   = IAND ( PHOTFLAG_MSKREJ(i), PHOTFLAG )
        IF ( OV > 0 .and. OV == PHOTFLAG_MSKREJ(i) ) THEN
             BADPHOT = .TRUE. ; REJECT  = .TRUE.
        ENDIF
      enddo

c ----------------------
c Check EARLY-epoch select logic (Mar 2015)

      IF ( .not. SELECT_EARLYLC(ep) ) REJECT = .TRUE.

c -------------------------------------
c July 11 2020
c  Check cuts on PSF and ZP ... doesn't change analysis,
c  but allows new OUT_EPOCH_IGNORE_FILE option to work properly.

c xxx      IF( RESTORE_DES3YR ) GOTO 600 ! skip ZP and PSF cut for DES3YR

      IF ( ZP < CUTWIN_ZP(1)   ) REJECT = .TRUE.
      IF ( ZP > CUTWIN_ZP(2)   ) REJECT = .TRUE.

      IF ( PSF < CUTWIN_PSF(1) ) REJECT = .TRUE.
      IF ( PSF > CUTWIN_PSF(2) ) REJECT = .TRUE.

c MJD cut
      LXMJD = ( MJD > CUTWIN_MJD_EXCLUDE(1) .and.
     &          MJD < CUTWIN_MJD_EXCLUDE(2) )
      IF ( LXMJD ) REJECT = .TRUE.

      IF ( MJD < CUTWIN_MJD(1) ) REJECT = .TRUE.
      IF ( MJD > CUTWIN_MJD(2) ) REJECT = .TRUE.

c - - - - - - - - - - - -
c reject epochs for filter band that has SNRMIN > 99
      if ( IFILT < 900 ) then
        if ( CUTWIN_SNRMIN_FILT(1,IFILT) > 99.9999 ) REJECT = .TRUE.
      endif

c check selected field.
      LTMP = DOALL_SNFIELD .or. (IDFIELD > 0)
      IF ( .NOT. LTMP ) REJECT = .TRUE.

c Sep 2020: apply SNR cut for non-detections - to reject crazy fluxes.
      IF ( PHOTFLAG_DETECT > 0 ) THEN
         NO_DETECT = ( IAND(PHOTFLAG,PHOTFLAG_DETECT) == 0 )
         SNR       = SNLC_FLUXCAL(EP) / SNLC_FLUXCAL_ERRTOT(EP)
         if ( NO_DETECT ) then
            if ( SNR < CUTWIN_SNR_NODETECT(1)  ) REJECT = .TRUE.
            if ( SNR > CUTWIN_SNR_NODETECT(2)  ) REJECT = .TRUE.
         endif
      ENDIF

c ----------------------------
 600  CONTINUE

c set return-function value
      PASS_EPOCH_CUTS = ( .not. REJECT)

c check option to count BAD PHOTOMETRY epochs based on PHOTFLAG
      IF ( BTEST(OPTMASK,0) ) THEN
         NEPOCH_TOT = NEPOCH_TOT + 1
         IF ( .NOT. REJECT)  NEPOCH_USE = NEPOCH_USE + 1
         IF ( BADPHOT ) THEN
            NEPOCH_BADPHOT     = NEPOCH_BADPHOT     + 1
            NEPOCH_BADPHOT_SUM = NEPOCH_BADPHOT_SUM + 1
         ENDIF
      ENDIF


      RETURN
      END     ! end PASS_EPOCH_CUTS

C = = = = = = = = = = = = = = = = =
CDECK  ID>,  PASS_EP_TREST. 
      LOGICAL FUNCTION PASS_EPOCH_TREST(z,PEAKMJD,EP)

C Created Feb 2021
C Return TRUE if epoch passes TREST cut

      IMPLICIT NONE

c input args
      REAL z, PEAKMJD  ! (I) redshift and peak MJD
      INTEGER EP       ! (I) epoch index to check Trest cut

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


      REAL MJD, ZZ, Trest
      LOGICAL VALID_PEAKMJD

C ----------- BEGIN ------------

      PASS_EPOCH_TREST = .TRUE.

      VALID_PEAKMJD = ( PEAKMJD > 40000.  )  ! valid PEAKMJD

c evaluate epoch cut in rest-frame
      IF ( VALID_PEAKMJD ) THEN
         ZZ = 1.0                       ! if no valid z
         IF ( z > 0.0 ) ZZ  = 1.0 + z   ! valid z
         MJD   = SNGL( SNLC8_MJD(EP) )
         Trest = (MJD - PEAKMJD) / ZZ

         PASS_EPOCH_TREST =
     &        ( Trest .GE. cutwin_Trest(1) .and.
     &          TRest .LE. cutwin_Trest(2) )
      ENDIF

      RETURN
      END     ! end PASS_EPOCH_TREST


C =============================
CDECK  ID>,  PASS_SNTYPE. 
      LOGICAL FUNCTION PASS_SNTYPE(itype)
c
c Created Feb 22 2021 [modified from SNTYPESTAT]
c
c Returns True if ITYPE passes cuts; returns false otherwise.
c Also increments global NACCEPT_TYPE if ITYPE is valid.
c
c Jul 12 2021: abort if ITYPE < 0
c Mar 08 2022: apply CUTWIN_SNTYPE
c -------------------------

      IMPLICIT NONE

c function args

      INTEGER  ITYPE  ! SN-integer type from data header

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER FNAM*12
      INTEGER i
      REAL RTYPE

C -------------- BEGIN --------------

      FNAM = 'PASS_SNTYPE'
      PASS_SNTYPE = .FALSE.

      IF ( ITYPE < 0 ) THEN
         write(c1err,61) ITYPE, SNLC_CCID
         write(c2err,62) MXTYPE
61       format('Invalid data header TYPE = ', I6, ' for CID=',A )
62       format('Valid TYPE range is 0 to ', I5)
         CALL MADABORT(FNAM, c1err, c2err)
      ENDIF

      do i = 1, NSNTYPE_IGNORE
        if ( SNTYPE_IGNORE(i) .EQ. ITYPE ) then
           PASS_SNTYPE = .FALSE.
           RETURN
        endif
      enddo

      RTYPE = float(ITYPE)
      IF ( RTYPE < CUTWIN_SNTYPE(1) ) RETURN
      IF ( RTYPE > CUTWIN_SNTYPE(2) ) RETURN

      IF ( NSNTYPE_LIST .LE. 0 ) THEN
         ! don't check  anything
         PASS_SNTYPE = .TRUE.
         RETURN
      ENDIF


      do i = 1, NSNTYPE_LIST
        if ( SNTYPE_LIST(i) .EQ. ITYPE ) PASS_SNTYPE = .TRUE.
      enddo

      IF ( PASS_SNTYPE ) THEN
         NACCEPT_TYPE = NACCEPT_TYPE + 1
      ELSE
         IF ( LDMP_SNFAIL ) then
              print*,'  ** WARNING ** CID= ',snlc_ccid,
     &       ' (TYPE=',itype,')  FAILS TYPE CUT '
         endif
      endif

      RETURN
      END  ! end PASS_SNTYPE


C ======================================
CDECK  ID>,  UNPSTR. 
      SUBROUTINE UNPACK_SNFITSIO_STR(NVAL,KEYNAME,STRING)

c
c  Created Jun 2011
c  Following a call to RD_SNFITSIO_STR(IROW, KEYNAME, STRING ..)
c  this routine unpacks and decodes the retured STRING and fills
c  the following arrays,
c
c  KEYNAME    filled array
c   FLT       ISNLC_IFILT_OBS
c   FIELD     ISNLC_IDFIELD & SNLC_FIELD
c
c Feb 11 2021: fix computation of LENS (length of STRING)
c -----------------------------

      IMPLICIT NONE

      INTEGER
     &   NVAL    ! (I) expect number of values to extract from STRING

      CHARACTER
     &   KEYNAME*(*)  ! (I) table par name read from fits file
     &  ,STRING*(*)   ! (I) string returned from RD_SNFITSIO_STR


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER iwd, LWD, NWD, LK, LENS, MSKOPT
      CHARACTER  CWD*80, FNAM*30
      LOGICAL LVAR_FLT, LVAR_FIELD

c functions
      INTEGER  FILTINDX_REPLACE, GET_IDFIELD

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ----------------- BEGIN --------------

      IF ( NVAL .LT. 0 ) RETURN  ! all epochs fail cut (May 16, 2012)

      FNAM = 'UNPACK_SNFITSIO_STR'

c determine variable type from KEYNAME

      LVAR_FLT   = .FALSE.
      LVAR_FIELD = .FALSE.

      IF ( KEYNAME(1:3) .EQ. 'FLT' ) THEN
        LVAR_FLT = .TRUE.
      ELSE IF ( KEYNAME(1:5) .EQ. 'FIELD' ) THEN
        LVAR_FIELD = .TRUE.
      ELSE
        c1err = 'Unrecognized KEYNAME = ' // KEYNAME
        c2err = 'Check FITS table.'
        CALL MADABORT('UNPACK_SNFITSIO_STR', c1err,c2err)
      ENDIF

c break up STRING into substrings
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      LENS   = INDEX(STRING//' ',' ' ) - 1  ! Feb 2021

cc      print*,' xxx UNPACK: ', LENS, '|', STRING, '|'
      NWD    = STORE_PARSE_WORDS(MSKOPT, STRING(1:LENS)//char(0),
     &            FNAM//char(0), LENS, 30 )

      IF  ( NWD .NE. NVAL ) THEN
        LK = INDEX(KEYNAME//' ' ,' ') -1
        CALL PRINT_PREABORT_BANNER("UNPACK_SNFITSIO_STR"//char(0),40)
        print*,'   NWD, NVAL = ', NWD, NVAL
        print*,'   SNLC_CCID = ', SNLC_CCID
        print*,'   KEYNAME   = ', KEYNAME,'      LENKEY=', LK
	print*,'   ISVAR_[FLT,FIELD] = ',
     &         LVAR_FLT, LVAR_FIELD
        print*,'   LEN(STRING) = ', LENS
        print*,'   STRING = ', STRING(1:1000)
        call flush(6)

        write(c1err,61) NWD, NVAL
     &
        write(c2err,62)
     &       SNLC_CCID(1:ISNLC_LENCCID)
     &      ,KEYNAME(1:LK)

61      format('NWD=',I5,' substrings, but expected NVAL=',I6)
62      format('CID=',A, 2x, 'KEYNAME=',A )
        CALL MADABORT('UNPACK_SNFITSIO_STR', c1err,c2err)

      ENDIF

      DO 100 iwd = 1, NWD

         CALL get_PARSE_WORD_fortran(iwd,CWD,LWD)

         if ( LVAR_FLT ) then
            ISNLC_IFILT_OBS(iwd) = FILTINDX_REPLACE(CWD)
         else if ( LVAR_FIELD ) then
            SNLC_FIELD(iwd)    = CWD(1:LWD)
            ISNLC_IDFIELD(iwd) = GET_IDFIELD(CWD)
         endif


100   CONTINUE

      RETURN
      END
C ========================================
CDECK  ID>,  FITSABORT. 
      SUBROUTINE CHECK_FITSABORT(IVERS,NRD,KEY)

c Created Jun 16, 2011
c ABORT if NRD = 0 or of NRD exceeds bound of MXEPOCH
c Call this routine after each fits-read for a REQIURED key.
c
c Note that NRD = -9 is OK because this means that
c all epochs failed the epoch-MASK  cuts.

      IMPLICIT NONE

      INTEGER
     &  IVERS   ! (I) version index
     & ,NRD     ! (I) Number of elements returned for fits key

      CHARACTER KEY*(*)  ! (I) name of fits key

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER VERSION*100
      INTEGER LK, LV

C ---------- BEGIN ----------


      IF ( NRD .EQ. 0 .or. NRD .GT. MXEPOCH ) THEN

         print*,' ERROR: NRD = ', NRD

         LK = INDEX(KEY,' ') - 1
         c1err = 'Non-existent FITS parameter: ' // KEY(1:LK)
     &           // ' for CID='// SNLC_CCID(1:ISNLC_LENCCID)

         VERSION  = VERSION_PHOTOMETRY(ivers)
         LV = INDEX(VERSION,' ') - 1
         c2err = 'Check fits files for version ' // VERSION(1:LV)

         CALL MADABORT("CHECK_FITSABORT",c1err, c2err)
      ENDIF

      RETURN
      END



C ==================================
CDECK  ID>,  PRINT_RDSN. 
      SUBROUTINE PRINT_RDSN()

C Called before SNANA_DRIVER, print one-line summary of SN that has
c been read/parsed.
C
C Apr 19 2022: replace REJECT_PRESCALE with MOD function to have
c              more predictable prints.
C
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER N_UPDATE_PS1, N_UPDATE_PS10, PS_UPDATE

C ------------- BEGIN -----------

c determine STDOUT_UPDATE logical to dump info

      N_UPDATE_PS1  = 50 ! update first 50 events
      N_UPDATE_PS10 = 300
      if ( REDUCE_STDOUT_BATCH ) then
         N_UPDATE_PS1  = 5
         N_UPDATE_PS10 = 100
      endif

      IF ( N_SNLC_PROC < N_UPDATE_PS1 ) THEN
         PS_UPDATE = 1
      ELSE IF ( N_SNLC_PROC < N_UPDATE_PS10 ) THEN
         PS_UPDATE = 10
      ELSE
         PS_UPDATE = 100
      ENDIF

      STDOUT_UPDATE = (MOD(N_SNLC_PROC,PS_UPDATE) .EQ. 0)
      if ( .NOT. STDOUT_UPDATE ) RETURN

      print*,' *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-' //
     &       '*-*-*-*-*-*-*-*-*-*-*-*-*-*-'

      IF ( SNLC_CASTCID .EQ. 'CHAR' ) then
          write(6,30) SNLC_CID, SNLC_CCID(1:ISNLC_LENCCID)
30        format(T4,'Assign integer CID=',I6,' for ', A)
      endif

      write(6,200)
     &      SNLC_CCID
     &    , ISNLC_NEWMJD_FOUND
     &    , ISNLC_NEWMJD_STORE

200   format(T5,' Done Reading CID ', A16,
     &       2x, 'NMJD(found,stored)=', I4,1x,I4 )

      CALL FLUSH(6)
      RETURN
      END      ! end PRINT_RDSN

C =================================
CDECK  ID>,  SET_HOSTGAL_PREFIX. 
      SUBROUTINE SET_HOSTGAL_PREFIX(IGAL,PREFIX,LENPRE)

c Feb 2019
c For inoput IGAL, return PREFIX = 'HOSTGAL' or 'HOSTGAL2', etc ..,
c along with LENPRE = length of PREFIX string.
c The output is used for parsing and writing output.
      IMPLICIT NONE
      INTEGER IGAL         ! (I) 1,2 ... host-match index
      CHARACTER PREFIX*20  ! (O) key prefix
      INTEGER LENPRE       ! (O) length of prefix string

      IF ( IGAL == 1 ) THEN
         PREFIX = 'HOSTGAL'; LENPRE=7
      ELSE
         write(PREFIX,20) IGAL
 20      format('HOSTGAL',I1.1)
         LENPRE = 8
      ENDIF
      RETURN
      END

C ==================================
CDECK  ID>,  SET_EPVAR_MISC. 
      SUBROUTINE SET_EPVAR_MISC(ep)
c Created Jul 11 2020:
c Compute a few misc variables from those read from data files
c   + SNLC_ZEROPT_forCUT(ep) based on cut in ADU or Npe
c   + SNLC_PSF_FWHM_ARCSEC(ep)

      IMPLICIT NONE
      INTEGER ep      ! (I) epoch index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      REAL   ZPADD_pe, GAIN
      REAL*8 PSFSIG1, PSFSIG2, PSFRAT, NEA

      EXTERNAL NoiseEquivAperture
      REAL*8   NoiseEquivAperture

c -------------- BEGIN ------------

      SNLC_ZEROPT_forCUT(ep) = SNLC_ZEROPT(ep) ! default is ADU

      if ( cutwin_zpNPE(1) > 0. ) then
         GAIN     = SNLC_GAIN(ep)

         if ( GAIN < 0.01 ) then
            GAIN = 0.001  ! -> results in very low ZP that should fail cut
         endif

         ZPADD_pe = 2.5*log10(GAIN)
         SNLC_ZEROPT_forCUT(ep) = SNLC_ZEROPT(ep) + ZPADD_pe
      endif

c if PSF unit is NEA, convert back to effected PSF-sigma;
c otherwise compute and store NEA
      IF ( UNIT_PSF_NEA ) then
         NEA     = DBLE(SNLC_PSF_NEA(ep))
         PSFSIG1 = SQRT(NEA/(4.0*PI))
         SNLC_PSF_SIG1(ep)  = SNGL(PSFSIG1)
         SNLC_PSF_SIG2(ep)  = 0.0
         SNLC_PSF_RATIO(ep) = 0.0
      else
         PSFSIG1 = DBLE(SNLC_PSF_SIG1(ep))
         PSFSIG2 = DBLE(SNLC_PSF_SIG2(ep))
         PSFRAT  = DBLE(SNLC_PSF_RATIO(ep))
         NEA     = NoiseEquivAperture(PSFSIG1,PSFSIG2,PSFRAT)
         SNLC_PSF_NEA(ep) = SNGL(NEA)
      endif

      SNLC_PSF_FWHM_ARCSEC(ep) =
     &   SNLC_PSF_SIG1(ep) * (SNLC_PIXSIZE * 2.355)

      RETURN
      END        ! end SET_EPVAR_MISC

C =================================
CDECK  ID>,  CHECKSTRING_CCID. 
      SUBROUTINE CHECKSTRING_CCID(CCID)

c  Jun 2016: abort if illegal char in SNLC_CCID

      IMPLICIT NONE
      CHARACTER CCID*(*)

c local
      INTEGER NBADCHAR, ichar
      PARAMETER  (NBADCHAR = 14)
      CHARACTER  BADCHAR_LIST*(NBADCHAR)
      CHARACTER  c1err*44, c2err*44, c1*2
C ----------- BEGIN ---------------

      BADCHAR_LIST = ':;!@#$%^&*()=?'

      DO 100 ichar = 1, NBADCHAR
         C1 = BADCHAR_LIST(ichar:ichar)
         IF ( INDEX(CCID,C1) > 0 ) THEN
            c1err = 'Invalid CCID name = ' // CCID
            c2err = 'because it contains invalid char = ' // c1
            CALL MADABORT('CHECKSTRING_CCID', c1err, c2err)
         ENDIF
100   CONTINUE

      RETURN
      END

C ==============================
CDECK  ID>,  CHKFLTKEY. 
      SUBROUTINE CHECK_FILTERS_KEY(FILTERS)

C Apr 2013  [code moved from PARSE_HEAD]
C Called from PARSE_HEAD for text files to check that
C FILTERS argument is always the same. Abort if the
C FILTERS argument ever changes.
C
C -------------

      IMPLICIT NONE

      CHARACTER FILTERS*(*)  ! (I) argument of "FILTERS:" key


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER   NFILT, IFILT, itmp, IFILT_OBS
      CHARACTER cfilt1*2

c functions
      INTEGER FILTINDX

C ---------------- BEGIN ----------------

      NFILT     = INDEX ( FILTERS//' ', ' ' ) - 1

      DO itmp       = 1, NFILT
         cfilt1     = FILTERS(itmp:itmp)
         ifilt_obs  = FILTINDX(cfilt1)
         IFILT      = IFILTDEF_INVMAP_SURVEY(ifilt_obs)

c check if sparse index is valid.
c Apr 2013: better error messaging.

         if ( ifilt .LE. 0 ) then
            CALL PRINT_PREABORT_BANNER("PARSE_HEAD"//char(0),40)
            print*,' FILTERS  defined in 1st data file:'
            print*,'      ', SURVEY_FILTERS(1:NFILTDEF_SURVEY)
            print*,' FILTERS  defined for '
     &           // SNLC_CCID(1:ISNLC_LENCCID), ' : '
            print*,'      ', FILTERS(1:NFILT)
            print*,'  --> FILTERS argument must be the same ',
     &                'in each data file. '

            c1err = 'Filter ' // cfilt1 // ' is unrecognized '
     &           // ' for CID=' // SNLC_CCID(1:ISNLC_LENCCID) // ' ; '

            c2err = 'see PRE-ABORT comments above.'
            CALL MADABORT("PARSE_HEAD", c1err, c2err)
         endif

      ENDDO                     ! end of ITMP loop

      RETURN
      END


C ===================================
CDECK  ID>,  PRSPAREN. 
      SUBROUTINE PARSE_PARENTHESES(INKEY,OUTSTR)

c Parse inKey to extract varName from ().
c Example:
c   Input : INKEY   = SIMSED_PARAM(COSANGLE)
c  -->
c   Ouptut: OUTSTR = COSANGLE
c
c ---------------------
      IMPLICIT NONE

c subroutine args
      CHARACTER INKEY*(*)   ! (I) input key with varname in ()
      CHARACTER OUTSTR*(*)  ! (O) string in ()


c local args
      INTEGER J1, J2, LK
      CHARACTER C1ERR*72, C2ERR*72
c -------------- BEGIN ---------------

      J1 = INDEX( INKEY , '(' )
      J2 = INDEX( INKEY , ')' )

      IF ( J1 .EQ. 0 .or. J2 .EQ. 0 ) THEN
         LK = INDEX( INKEY, ' ' ) - 1
         c1err = 'Invalid INKEY = ' // INKEY(1:LK)
         c2err = 'Expecting to find key-string  SIMSED_XXX(PARNAME)'
         CALL MADABORT("PARSE_PARENTHESES", c1err,c2err)
      ENDIF

      OUTSTR = INKEY(j1+1:j2-1)

      RETURN
      END    ! end of PARSE_PARENTHESES


C ====================================
CDECK  ID>,  PARSE_CID. 
      SUBROUTINE PARSE_CID ( ccid, iauc, cid, USECID )
c
c Convert character string CCID into integer CID.
c Returns logical USECID=T if this CID should be processed.
c
c
c Jul 28 2014; allow ABORT_ON_DUPLCID=F to count duplicates without aborting
c
c Jul 31 2015: move GET_INTERP_MJDLIST call before LCIDSELECT call
c
c Dec 2 2015: pass IAUC arg.
c
c ---------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


      CHARACTER  CCID*(*)  ! (I) character string for CID
      CHARACTER  IAUC*(*)  ! (I) char string for IAUC name
      INTEGER    CID       ! (O) integer CID
      LOGICAL    USECID    ! (O) T => process this CID

c local var

      INTEGER LCHAR, NMJD, ISTAT
      LOGICAL  USECID_LOCAL, ADDFLAG, LDUPL

      REAL*8  MJD8LIST(MXINTERP)

c function
      INTEGER CIDASSIGN, EXEC_CIDMASK
      LOGICAL LCIDSELECT

C --------------- BEGIN --------------

      CID = 0
      USECID = .FALSE.

c check if this CID should be processed.
      LCHAR = INDEX ( CCID, ' ' ) - 1
      LCHAR = MIN(MXCHAR_CCID,LCHAR) ! check limit on Number of chars

c convert char-string to integer CID
      CID = CIDASSIGN(CCID)

      IF ( CID .LE. 0 ) THEN
        c1err = 'Cannot determine integer CID for: ' // CCID
        write(c2err,602)  LCHAR
602     format('LEN(CCID) = ', I5 )
        CALL MADABORT("PARSE_CID", c1err, c2err)
      ENDIF

      IF ( CID > MXCID ) THEN
        write(c1err,611) CID, MXCID
        C2err = '   '
611     format('CID=',I9,' exceeds MXCID=',I9 )
        CALL MADABORT("PARSE_CID", c1err, c2err)
      ENDIF


c check for CIDs to interpolate (May 18, 2012)
      CALL GET_INTERP_MJDLIST(CCID, NMJD, MJD8LIST, ADDFLAG)
      IF ( ADDFLAG ) THEN
          NCCID_LIST = NCCID_LIST + 1
          SNCCID_LIST(NCCID_LIST) = CCID  ! Dec 4 2012
          USECID_LOCAL = .TRUE.
          GOTO 800
      ENDIF

c ----------------------------------------------------
      IF ( .NOT. LCIDSELECT(cid,ccid,iauc) ) RETURN
      SNLC_CCID      = CCID    ! in case CCID -> IAUC (Dec 3, 2015)
      ISNLC_LENCCID  = INDEX(CCID,' ') - 1  ! Mar 20 2016
      USECID_LOCAL   = .TRUE.
      GOTO 800

c ---------------------------
800   CONTINUE

      IF ( CID < MXCID_CHECK ) THEN
        ISTAT = EXEC_CIDMASK(2,CID)  ! returns 1 if CID bit is set
        LDUPL = (ISTAT > 0 )
      ELSE
        LDUPL = .FALSE. ! cannot check duplicates for very large CID
      ENDIF

      IF ( USECID_LOCAL ) THEN

c if this CID has already been used (found), abort.

        if ( LDUPL  ) THEN

          IF ( ABORT_ON_DUPLCID ) then
            write(c1err,801) CID, CCID(1:LCHAR)
801         format('CID= ',I9, ' (',A, ') appears more than once; ' )
            c2err = 'each CID can appear only once.'
            CALL MADABORT("PARSE_CID", c1err, c2err)
          ELSE
             print*,' *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-' //
     &            '*-*-*-*-*-*-*-*-*-*-*-*-*-*-'
             write(6,866) CCID
 866         format(T10,'!!! DUPLICATE WARNING: reject CID=',A)
             call flush(6)
             N_DUPLICATE_CID = N_DUPLICATE_CID + 1
             return  ! return with USECID=F
          endif
        endif

        IF ( CID < MXCID_CHECK ) THEN
           ISTAT = EXEC_CIDMASK(1,CID)  ! set CID bit
        ENDIF

        NACCEPT_CID = NACCEPT_CID + 1
        USECID      = .TRUE.

      ELSE

        if ( LDMP_SNFAIL ) then
           print*,'  ** WARNING ** CID ',cid,' FAILS CID CUT '
           CALL FLUSH(6)
        endif

      ENDIF

      RETURN
      END  ! end of PARSE_CID


C ============================================
CDECK  ID>,  GET_IDSURVEY. 
      INTEGER FUNCTION GET_IDSURVEY(SURVEY)

      CHARACTER SURVEY*(*)  ! (I) name of survey

c local var

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


      INTEGER ID, j1, j2
      LOGICAL LMATCH
C ---------- BEGIN ------------

      ID = -9 ; GET_IDSURVEY=-9

      DO 101 i = 1, NSURVEY_LIST
         j1 = index(SURVEY,' ') - 1
         j2 = index(SURVEY_NAME_LIST(i),' ') - 1
         if ( j1 .NE. j2 ) goto 101
         LMATCH = ( SURVEY(1:j1) .EQ. SURVEY_NAME_LIST(i)(1:j2) )
         if ( LMATCH )  ID = IDSURVEY_LIST(i)
101   CONTINUE

      GET_IDSURVEY = ID

      RETURN
      END    ! end GET_IDSURVEY



C =============================================
CDECK  ID>,  CIDASSIGN. 
      INTEGER FUNCTION CIDASSIGN(CCID)
c
c Created May 28, 2008 by R.Kessler
c Assign integer CID to character string CCID
c If CCID is already an integer, then CID = CCID;
c otherwise set CID = IFILE.
c
c Note that if a string-named SN appears in
c multiple PHOTOMETRY version, it can have
c a different CID in each case. For integer
c CIDs (like SDSS), the CID is always the same.
c
c
c ---------------------

      IMPLICIT NONE
      CHARACTER CCID*(*)  ! (I)

c local var

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IERR, CID, LCHAR

c ----------- BEGIN -------------

      CID = -1 ; IERR=0
      read( ccid, 20 , iostat = IERR ) CID
20    format(I10)    ! was I8

      IF ( IERR .EQ. 0 ) THEN  ! CCID is an integer
         SNLC_CASTCID = 'INT'
      ELSE
         LCHAR = INDEX ( CCID, ' ' ) - 1
         CID   = ABSO_INDEX
         SNLC_CASTCID = 'CHAR'
      ENDIF

      CIDASSIGN = CID

      RETURN
      END



C ==============================
CDECK  ID>,  PARSE_FILTERSTRING. 
      SUBROUTINE PARSE_FILTSTRING(OPT,string, NFILT, IFILTDEF, XFILTVAL)

c -------------------------------
c Created May 2008 by R.Kessler
c
c Translate input STRING into filter indices
c and values. Assume STRING is of the form
c
c  STRING = 'cfilt1 xval1  cfilt2  xval2 cfilt2 xval2 ...'
c
c where a float-value follows each single-char
c filter-string.
c
c Oct 26 2015: replace MXFILT_OBS arg with NFILT
c Dec 27 2015: fix bug initializing IFILTDEF and XFILTVAL
c              Loop 1-NFILT instead of 1-MXFILT_OBS
c
c May 20 2016: declare output arrays (MXFILT_OBS) instead of (NFILT)
c
c Feb 20 2017: update to allow multiple bands gluded together.
c              'gri .01'  is equivalent to  'g .01  r .01  i .01'
c
c Feb 4 2020:
c   + check 'ALL' or 'all' to set same mag for all bands.
c   + fix bug parsing  'abcd 0.02' ; last band value wasn't set.
c
c --------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c subroutine args
      CHARACTER string*(*)  ! (I) string to parse

      INTEGER
     &   OPT                  ! (I) 1=> error check obs filter
     &  ,NFILT                ! (O) number of filters in string
     &  ,IFILTDEF(MXFILT_OBS) ! (O) absolute filter indices

      REAL
     &   XFILTVAL(MXFILT_OBS)   ! (O) float values

c local var

      INTEGER iwd, NWD, ifilt_tmp, LEN, NFILT_TMP, NFILT_LAST, i
      INTEGER MSKOPT
      CHARACTER cwd*(MXCHAR_FILEWORD), band*2, FNAM*30
      REAL VAL
      LOGICAL LERR

c function
      INTEGER FILTINDX
      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS
c --------------- BEGIN ------------

      NFILT = 0
      IFILT_TMP = 0

      FNAM = 'PARSE_FILTSTRING'
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      NWD = STORE_PARSE_WORDS(MSKOPT,STRING//char(0),
     &          FNAM//char(0), 80, 30)

      DO i = 1, MXFILT_OBS
        IFILTDEF(i) = 0
        XFILTVAL(i) = 0.  ! init output to zero
      ENDDO

c - - - - - - - - - - - - -
c Feb 2020: check 'all' option to set same mag error for all filters
      IF ( STRING(1:3) .EQ. 'ALL' .or. STRING(1:3).EQ. 'all' ) then
         iwd = 2
         CALL get_PARSE_WORD_fortran(iwd,cwd,LEN) ! read mag_err
         read(cwd,*) VAL
         do ifilt_tmp = 1, NFILTDEF_SURVEY
           IFILTDEF(ifilt_tmp) = IFILTDEF_MAP_SURVEY(ifilt_tmp)
           XFILTVAL(ifilt_tmp) = VAL
         enddo
         NFILT = NFILTDEF_SURVEY
         RETURN
      ENDIF

c - - - - - - - - -

      NFILT_LAST = 0
      DO 200 iwd = 1, NWD

         CALL get_PARSE_WORD_fortran(iwd,cwd,LEN)

         if ( IFILT_TMP == 0 ) then
            NFILT_LAST = NFILT
            NFILT_TMP  = LEN
            do i = 1, NFILT_TMP
              BAND            = cwd(i:i)
              NFILT           = NFILT + 1
              IFILT_TMP       = FILTINDX(BAND)
              IFILTDEF(NFILT) = IFILT_TMP

c require valid observer-filter if OPT=1
              LERR = IFILTDEF_INVMAP_SURVEY(IFILT_TMP) .LE. 0
              if ( LERR .and. OPT==1 ) then
                print*,'  SURVEY_FILTERS = ', SURVEY_FILTERS
                LEN = index(cwd,' ') - 1
                c1err = 'Invalid obs-frame filter = '''
     &             // BAND // ''' from nml string'
                c2err = '= ''' // string(1:60) // '''  '
                CALL MADABORT('PARSE_FILTSTRING', c1err, c2err )
              endif
           enddo
         else
            read(cwd,*) VAL
            do i = NFILT_LAST+1, NFILT_LAST+NFILT_TMP
               XFILTVAL(i) = VAL
            enddo
            ifilt_tmp = 0
         endif
200   CONTINUE


      RETURN
      END   ! PARSE_FILTSTRING


C ====================================================
CDECK  ID>,  PARSE_INTLIST. 
      INTEGER FUNCTION PARSE_INTLIST(STRING_INLIST,OUTLIST)

c Created Jan 25 2018
c Translate comma-separated list of integers in STRING_LIST
c into array of integers (OUTLIST).
c Function returns number of integers in OUTLIST array.
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


      INTEGER   MXINT
      PARAMETER (MXINT=10)

      CHARACTER STRING_INLIST*60    ! (I) comma-separated list of integers
      INTEGER   OUTLIST(MXINT)      ! (O) output array of integers

c local arg

      INTEGER iwd, NWD, LEN, MSKOPT
      CHARACTER CWD*60, C1ERR*72, C2ERR*72, FNAM*30
C function
      INTEGER STORE_PARSE_WORDS

C ---------------- BEGIN ----------------
      FNAM   = 'PARSE_INTLIST'
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      LEN    = INDEX(STRING_INLIST,' ') - 1
      NWD    = STORE_PARSE_WORDS(MSKOPT,STRING_INLIST//char(0),
     &            FNAM//char(0), LEN, 30)

      IF ( NWD > MXINT ) THEN
         write(c1err,61) NWD, MXINT
 61      format('NWD=',I2,' exceeds bound of MXINT=',I2)
         write(c2err,62) STRING_INLIST(1:LEN)
 62      format('STRING_INLIST=',A)
         CALL MADABORT("PARSE_INTLIST", c1err, c2err )
      ENDIF

      DO 200 iwd = 1, NWD
         CALL get_PARSE_WORD_fortran(iwd,cwd,LEN)
         READ(cwd,*) OUTLIST(iwd)
ccc         print*,' xxx ', iwd, OUTLIST(iwd)
 200  CONTINUE

      OUTLIST(NWD+1) = 0

      PARSE_INTLIST = NWD
      RETURN
      END

C ===========================================
CDECK  ID>,  PARSE_COMMASEP_LIST. 
      SUBROUTINE PARSE_COMMASEP_LIST(KEY,LINE)

c Created May 30 2019
c Parse command LINE argument and load global array
c based on KEY value.
c E.g., KEY = 'SNCCID_LIST and  LINE = '2004hq,2006ab' ->
c    SNCCID_LIST = '2004hq', '2006ab'
c

      IMPLICIT NONE
      CHARACTER KEY*(*), LINE*(*)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER  MSKOPT, NWD, iwd, LL
      INTEGER  STORE_PARSE_WORDS
      CHARACTER WDTMP*60, FNAM*30
      EXTERNAL STORE_PARSE_WORDS

C --------------- BEGIN ------------

      FNAM = 'PARSE_COMMASEP_LIST'
      LL = INDEX(LINE,' ') - 1
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      NWD    = STORE_PARSE_WORDS(MSKOPT,LINE(1:LL)//char(0),
     &             FNAM//char(0), LL, 30)

      DO iwd = 1, NWD

         if ( KEY .EQ. 'SNCCID_LIST' ) then
            CALL get_PARSE_WORD_fortran(iwd,
     &                   SNCCID_LIST(iwd), LL)

         else if ( KEY .EQ. 'SNCCID_IGNORE' ) then
            CALL get_PARSE_WORD_fortran(iwd,
     &                   SNCCID_IGNORE(iwd), LL)

         else if ( KEY .EQ. 'VERSION_PHOTOMETRY' ) then
            CALL get_PARSE_WORD_fortran(iwd,
     &                   VERSION_PHOTOMETRY(iwd), LL)

         else if ( KEY .EQ. 'PHOTFLAG_BITLIST' ) then
            CALL get_PARSE_WORD_fortran(iwd, WDTMP, LL)
            read(WDTMP,*) PHOTFLAG_BITLIST_REJECT(iwd)
         endif

c        LL = INDEX(SNCCID_LIST(iwd),' ') - 1
c        print*,' xxx SNCCID = |', SNCCID_LIST(iwd)(1:LL), '|'
      ENDDO

      RETURN
      END    ! PARSE_COMMASEP_LIST

C ====================================================
CDECK  ID>,  PARSE_NML_STRLIST. 
      INTEGER FUNCTION PARSE_NML_STRINGLIST(STRLIST,NCHAR)

c Created Mar 12 2015 by R.Kessler
c Function returns number of non-null elements,
c and parses strings separated by blanks.
c
c The following inputs all produce the same output
c
c Input:
c      STRLIST = 'E1', 'E2', 'S1', 'S2'
c          or
c      STRLIST = 'E1 E2 S1 S2'
c          or
c      STRLIST = 'E1 E2',  'S1 S2'

c all produce  Output:
c    STRLIST = 'E1', 'E2', 'S1', 'S2'
c    and FUN=4
c
c ------------------------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


c +CDE,PARSECOM.

      INTEGER NCHAR   ! (I)
      CHARACTER STRLIST(MXLISTNML)*(NCHAR) ! (I,O)

c local var

      CHARACTER STRLIST_LOCAL(MXLISTNML)*(NCHAR), FNAM*30
      INTEGER i, j, NLIST, iwd, NWD, LL, MSKOPT

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------- BEGIN ------------

      FNAM = 'PARSE_NML_STRINGLIST'

      NLIST = 0
      MSKOPT = MSKOPT_PARSE_WORDS_STRING

c transfer input string to local string
      DO i = 1, MXLISTNML
         STRLIST_LOCAL(i) = STRLIST(i)
      ENDDO

      i = 1
      DO WHILE ( STRLIST_LOCAL(i) .NE. '' )

c remove optional '+' symbols between strings, and substitute blank.
         DO j = 1, NCHAR
           IF ( STRLIST_LOCAL(i)(j:j) .EQ. '+' ) then
              STRLIST_LOCAL(i)(j:j) = ' '
           endif
         ENDDO

         NWD = STORE_PARSE_WORDS(MSKOPT,STRLIST_LOCAL(i)//char(0),
     &            FNAM//char(0), 100, 30 )

         DO iwd = 1, NWD
            NLIST = NLIST + 1
            CALL get_PARSE_WORD_fortran(iwd,STRLIST(NLIST),LL)
         ENDDO

         i = i + 1

      END DO  ! end while

      PARSE_NML_STRINGLIST = NLIST

      RETURN
      END  ! end of PARSE_NML_STRINGLIST

C ====================================================
CDECK  ID>,  CIDSTR. 
      SUBROUTINE CIDSTRING(CID,CCID,LENCCID)
c
c Created Jan 15, 2011
c If integer CID < 1 million, return 6-char CCID and LENCCID=6;
c otherwise return 8-char CCID and LENCCID=8.
c
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



      INTEGER   CID                ! (I) integer cand. id
      CHARACTER CCID*(MXCHAR_CCID)  ! (O) char-string for CCID
      INTEGER   LENCCID            ! (O) length of string

c local
      CHARACTER C1ERR*72, C2ERR*72

c ----------- BEGIN -----------

      IF ( CID .LT. 1000000 ) THEN    ! 1 million
         write(ccid,26) CID
26       format(I6.6)
         LENCCID = 6
      ELSE IF ( CID < 100000000 ) THEN  ! 100 million
         write(ccid,28) CID
28       format(I8.8)
         LENCCID = 8
      ELSE IF ( CID < MXCID ) THEN
         write(ccid,29) CID
29       format(I9.9)
         LENCCID = 9
      ELSE
         write(C1ERR,66) CID, MXCID
66       format('CID=',I9,' exceeds bound (MXCID=', I9,')' )
         C2err = '   '
         CALL MADABORT("CIDSTRING", c1err, c2err )
      ENDIF

      RETURN
      END

C ===============================================
CDECK  ID>,  FILTREPLACE. 
      INTEGER FUNCTION FILTINDX_REPLACE ( cfilt )

c Created Jun 2013 by RK.
c Same as FILTINDX, but apply FILTER_REPLACE (see INIT_FILTER_REPLACE)
c Examples:
c   FILTER_REPLACE = ''       : do exactly the same thing as FILTINDX.
c   FILTER_REPLACE = 'U -> u' : for U filter, return index for 'u'
c
c ------

      IMPLICIT NONE
      character cfilt*(*)  ! (I) filter name to parse

c local args

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER   IFILTDEF_ORIG
c  function
      INTEGER FILTINDX

C ---------------- BEGIN ---------------
      IFILTDEF_ORIG    =  FILTINDX(CFILT)
      FILTINDX_REPLACE =  IFILTOBS_REPLACE(IFILTDEF_ORIG)

      RETURN
      END

C ===============================================
CDECK  ID>,  FILTINDX. 
      INTEGER FUNCTION FILTINDX ( cfilt )
c
c May 2008 R.Kessler
c Returns absolute integer filter-index 1:MXFLT_ALL by
c parsing character name "cfilt".
c Assumes that last character is the 1-char symbol;
c i.e, SDSS-g => g,  CTIO4m-R => R, etc ...

      IMPLICIT NONE
      character cfilt*(*)  ! (I) filter name to parse


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK



      integer LL, ifilt
      character cfilt1*1, ctest*1


c ----------- BEGIN -----------

      FILTINDX = 0

      LL  = index(CFILT//' ',' ' ) - 1
      cfilt1 = CFILT(LL:LL)

      DO ifilt = 1, MXFILT_ALL
        ctest = filtdef_string(ifilt:ifilt)
        if ( ctest(1:1) .eq. cfilt1(1:1) ) then
           FILTINDX = ifilt
           return
        endif
      ENDDO

      RETURN
      END

C ==============================
CDECK  ID>,  ISBXFILT. 
      LOGICAL FUNCTION ISBXFILT(IFILT,NAME,FRAME)

c Created May 2012
c Set global locical EXIST_BXFILT_OBS[REST]=T if this
c X-filter contains 'BX'.
c

      IMPLICIT NONE

c function args

      INTEGER IFILT  ! absolute filter index
      CHARACTER
     &   NAME*(*)    ! full name of filter
     &  ,FRAME*(*)   ! 'OBS' or 'REST'


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER JX
      CHARACTER C2*2

C ----------------- BEGIN ----------------

      ISBXFILT = .FALSE.
      IF ( IFILT .NE. IFILT_BESS_BX ) RETURN

      JX = INDEX(NAME,'X')

      IF ( JX .GT. 1 ) THEN
          C2 = NAME(JX-1:JX)
          IF( C2 .EQ. 'BX' ) then
             ISBXFILT = .TRUE.
          else
             return
          endif

c now that ISBXFILT=T  set global logical
          IF ( FRAME .EQ. 'OBS'  ) EXIST_BXFILT_OBS  = .TRUE.
          IF ( FRAME .EQ. 'REST' ) EXIST_BXFILT_REST = .TRUE.

      ELSE

          IF ( FRAME .EQ. 'OBS'   ) ISBXFILT = EXIST_BXFILT_OBS
          IF ( FRAME .EQ. 'REST'  ) ISBXFILT = EXIST_BXFILT_REST

      ENDIF

      RETURN
      END



C ================================================
CDECK  ID>,  GET_IDFIELD. 
      INTEGER FUNCTION GET_IDFIELD ( field_name )
c
c May 2009
c Return integer ID for this FIELD.
c IDFIELD is defined $SNDATA_ROOT/SURVEY.DEF
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      character field_name*(*)  ! name of telescope

c local
      character field_upper*60
      INTEGER LL, i
c --------------- BEGIN -----------------

      GET_IDFIELD = -9

      CALL UPCASE(field_name, field_upper) ! returns field_upper

      if ( field_upper(1:3) .EQ. 'ALL' ) then
        GET_IDFIELD = 0
        return
      endif

      DO i = 1, NIDFIELD_LIST  ! user-list of fields
        LL = INDEX(SNFIELD_LIST(i),' ' ) - 1
        IF ( FIELD_UPPER(1:LL) .EQ. SNFIELD_LIST(i)(1:LL) ) THEN
          GET_IDFIELD = IDFIELD_LIST(i)
        ENDIF
      END DO

      RETURN
      END         ! end of GET_IDFIELD

C ==================================
CDECK  ID>,  ENDMJD_PROC. 
      SUBROUTINE ENDMJD_PROC(NEWMJD)
c
c Aug 2007, R.Kessler
c
c Erase bad mesaurements.
c If all measurements (filters) are erased, then erase
c this MJD.
c
c May 9 2016: modify IGNORE logic
c
c ---------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c input args
      INTEGER NEWMJD  ! index for SN and MJD

c local args

      INTEGER
     &   EPMIN, EPMAX, ep, ep2
     &  ,ifilt_obs, ifilt_obs2, ifilt
     &  ,NEPSKIP, NFILT, EPMAX_OLD, NMOVED

      REAL FLUXCAL, FLUXCAL_ERR

      LOGICAL
     &   LVALID(MXFILT_ALL)
     &  ,LMOVED(MXFILT_ALL)
     &  ,LTMP, IGNORE

      character cfilt1

C ------------- BEGIN -------------

      NFILT = ISNLC_NFILT_NEWMJD(NEWMJD)

c for this NEWMJD, erase NULL measurements to save
c memory for old files with 5 filters per _line even
c when only 1 filter has data.
c Note that valid measurements are re-sorted
c and EPMAX is lowered.

      EPMIN  =  ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
      EPMAX  =  ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

      do ifilt_obs = 1, MXFILT_ALL
          LVALID(ifilt_obs) = .FALSE.
          LMOVED(ifilt_obs) = .FALSE.
      enddo

      NEPSKIP = 0

      DO 100 ep      = EPMIN, EPMAX
         ifilt_obs   = ISNLC_IFILT_OBS(ep)
         fluxcal     = SNLC_FLUXCAL(ep)
         fluxcal_err = SNLC_FLUXCAL_ERRTOT(ep)
cc         mag         = SNLC_MAG(ep)
         IGNORE      = (fluxcal_err < 0.0 ) .and.
     &         (.not. REFORMAT_SAVE_BADEPOCHS )

c make sure filter is valid by checking that
c the flux-error is non-negative.

         IFILT = IFILTDEF_INVMAP_SURVEY(IFILT_OBS)
         if ( IFILT .LT. 1 .or. IFILT .GT. NFILTDEF_SURVEY ) then

            cfilt1 = FILTDEF_STRING(ifilt_obs:ifilt_obs)

            write(c1err,650)
     &         ifilt_obs, cfilt1, SNLC8_MJD(EPMIN), SNLC_CCID
650         format('Invalid IFILT_OBS=',I3, '(',A,')' ,
     &          '  at MJD=',F9.3, 3x,'CID=',A)

            write(c2err,651) SURVEY_FILTERS(1:NFILTDEF_SURVEY)
651         format('Valid IFILT_OBS  are ', A )

            CALL MADABORT("ENDMJD_PROC", c1err, c2err )
         endif

         LMOVED(ifilt_obs) = .FALSE.

c check for valid measure.
c Set LSORT=T for any invalid measurement

         LTMP  =  (.not. IGNORE )
     &     .and.  (CUTWIN_SNRMIN_FILT(1,ifilt) < 100.0)

         if ( LTMP ) then
            LVALID(ifilt_obs) = .TRUE.
         else
           NEPSKIP =  NEPSKIP + 1
           LVALID(ifilt_obs) = .FALSE.
         endif
100   CONTINUE

cc      print*,' xxx LVALID = ', LVALID

c -------------------------------------------------------
c increment NEWMJD and NEPOCH if we have not erased
c all measurements

      if ( NEPSKIP .EQ. NFILT ) RETURN ! erase entire MJD

c ----------------

      ISNLC_NEWMJD_STORE = NEWMJD  ! increment new MJD

      ISNLC_NEPOCH_STORE = ISNLC_NEPOCH_STORE +
     &   ISNLC_NFILT_NEWMJD(NEWMJD)

      if ( NEPSKIP .EQ. 0 ) RETURN  ! all OK => bail

c if we get here, then there is at least one invalid
c measurement (epoch) for this NEWMJD; re-sort
c epochs to skip bad epochs.

      EPMAX_OLD = EPMAX
      EPMAX     = EPMAX_OLD - NEPSKIP

      IF ( EPMAX .LT. EPMIN ) then

        write(c1err,660) EPMIN,EPMAX_OLD, EPMIN, EPMAX,
     &       NFILT, NEPSKIP
660     format('EPMIN,MAX=',2I4, ' -> ', 2I4, 3x,
     &       'NEPFILT=',I2, 2x,  'NEPSKIP=',I2  )
        write(c2err,661) SNLC8_MJD(EPMIN), SNLC_CCID
661     format('at MJD = ', F9.3, 4x, 'CID=', A )

        CALL MADABORT("ENDMJD_PROC", c1err, c2err )

      ENDIF


c loop over epochs and re-sort with NULL measurements removed.
c Logic is tricky.

      DO 200 ep = EPMIN, EPMAX_OLD

         ifilt_obs   = ISNLC_IFILT_OBS(ep)
         if ( LVALID(ifilt_obs) ) goto 200

c here we have invalid measure at epoch EP ...
c copy next valid epoch here.

         NMOVED = 0
         DO 202 ep2 = ep+1, EPMAX_OLD
           ifilt_obs2   = ISNLC_IFILT_OBS(ep2)
           LTMP = .NOT. LMOVED(ifilt_obs2) .and. NMOVED.EQ.0
           if ( LVALID(ifilt_obs2) .and. LTMP ) then
              CALL MOVE_SNLC_ARRAYS(ep,ep2)  ! move ep2 -> ep
              LMOVED(ifilt_obs2) = .TRUE.
              LVALID(ifilt_obs2) = .FALSE.
              NMOVED = NMOVED + 1
           endif

202      CONTINUE

200   CONTINUE  ! end of 'ep' loop

c ---------------------------------------
c adjust global variables that depend on NEPSKIP or EPMAX

       ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD) = EPMIN
       ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD) = EPMAX

       ISNLC_NEPOCH_STORE =
     & ISNLC_NEPOCH_STORE - NEPSKIP

       ISNLC_NEPOCH_FOUND =
     & ISNLC_NEPOCH_FOUND - NEPSKIP

       ISNLC_NFILT_NEWMJD(NEWMJD) =
     & ISNLC_NFILT_NEWMJD(NEWMJD) - NEPSKIP

      RETURN
      END

C ===================================
CDECK  ID>,  MOVE_SNLC_ARRAYS. 
      SUBROUTINE MOVE_SNLC_ARRAYS(ep1,ep2)
c
c
c Jun 25 2019: include SIM_XXX arrays
c Nov 12 2019: check LSIM_MAGOBS to set SIM_EPMAGOBS(ep)
c Feb 17 2021:
c   for I/O refactor, include SNLC_ZEROPT_forCUTS and SNLC_PSF_FWHM
c Mar 01 2021: include SNLC_PSF_NEA

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER ep1, ep2  ! (I)

C ------------- BEGIN ------------

      SNLC8_MJD(ep1)           = SNLC8_MJD(ep2)
      ISNLC_IDFIELD(ep1)       = ISNLC_IDFIELD(ep2)
      SNLC_FIELD(ep1)          = SNLC_FIELD(ep2)
      ISNLC_IFILT_OBS(ep1)     = ISNLC_IFILT_OBS(ep2)
      SNLC_FLUXCAL(ep1)        = SNLC_FLUXCAL(ep2)
      SNLC_FLUXCAL_ERRTOT(ep1) = SNLC_FLUXCAL_ERRTOT(ep2)
      ISNLC_PHOTFLAG(ep1)      = ISNLC_PHOTFLAG(ep2)
      SNLC_PHOTPROB(ep1)       = SNLC_PHOTPROB(ep2)
      SNLC_PSF_SIG1(ep1)       = SNLC_PSF_SIG1(ep2)
      SNLC_PSF_SIG2(ep1)       = SNLC_PSF_SIG2(ep2)
      SNLC_PSF_RATIO(ep1)      = SNLC_PSF_RATIO(ep2)
      SNLC_PSF_NEA(ep1)        = SNLC_PSF_NEA(ep2)
      SNLC_SKYSIG(ep1)         = SNLC_SKYSIG(ep2)
      SNLC_SKYSIG_T(ep1)       = SNLC_SKYSIG_T(ep2)
      SNLC_RDNOISE(ep1)        = SNLC_RDNOISE(ep2)
      SNLC_ZEROPT(ep1)         = SNLC_ZEROPT(ep2)
      SNLC_ZEROPT_ERR(ep1)     = SNLC_ZEROPT_ERR(ep2)
      SNLC_GAIN(ep1)           = SNLC_GAIN(ep2)
      SNLC_XPIX(ep1)           = SNLC_XPIX(ep2)
      SNLC_YPIX(ep1)           = SNLC_YPIX(ep2)

      SNLC_ZEROPT_forCUT(ep1)   = SNLC_ZEROPT_forCUT(ep2)
      SNLC_PSF_FWHM_ARCSEC(ep1) = SNLC_PSF_FWHM_ARCSEC(ep2)

c beware that CCDNUM is read from header, and also from
c PHOT section of TEXT format ... but not read from PHOT-FITS file
      ISNLC_CCDNUM(EP1)        = ISNLC_CCDNUM(EP2)
      ISNLC_IMGNUM(EP1)        = ISNLC_IMGNUM(EP2)

      IF ( ISJOB_SIM ) THEN
        SIM_EPMAGOBS(EP1)          = SIM_EPMAGOBS(EP2)
        SIM_EPFLUXCAL(EP1)         = SIM_EPFLUXCAL(EP2)
        SIM_EPCHI2FLUX(EP1)        = SIM_EPCHI2FLUX(EP2)
        SIM_EPPULL(EP1)            = SIM_EPPULL(EP2)
      ENDIF

      IF ( LSIM_SNANA ) THEN
        SIM_EPFLUXCAL_HOSTERR(EP1) = SIM_EPFLUXCAL_HOSTERR(EP2)
        SIM_EPSNRMON(EP1)          = SIM_EPSNRMON(EP2)
      ENDIF

c - - -
      SNLC_MAG(ep1)            = SNLC_MAG(ep2)
      SNLC_MAG_ERRPLUS(ep1)    = SNLC_MAG_ERRPLUS(ep2)
      SNLC_MAG_ERRMINUS(ep1)   = SNLC_MAG_ERRMINUS(ep2)

      RETURN
      END    ! end MOVE_SNLC_ARRAYS

C ===================================
CDECK  ID>,  INIT_SNLC. 
      SUBROUTINE INIT_SNLC()
c
c Init SNLC_XXX arrays for this SN
c Called for each SN.
c
c Nov 22 2017: use NEP_RESET to reduce CPU time for init
c Feb 07 2021: rename INIT_SNDATA -> INIT_SNLC to avoid confusion
c               with INIT_SNDATA in sntools.c
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



C +CDE,EARLYCOM. inserted below by ypatchy. 

      REAL DT_SAMENIGHT
ccc   PARAMETER (DT_SAMENIGHT = 0.333) ! same night within 1/3 day = 8 hr
      PARAMETER (DT_SAMENIGHT = 0.400) ! same night within 0.4 day

c variables for selecting the early part of a light curve
      INTEGER    NOBS_EARLYLC, NNIGHT_EARLYLC
      INTEGER    NPHOTMASK_START_EARLYLC
      REAL       NSNR_START_EARLYLC
      REAL       MJDLAST_EARLYLC, MJDLAST_SELECT

      COMMON / EARLYCOM /
     &   NOBS_EARLYLC, NNIGHT_EARLYLC,
     &   NPHOTMASK_START_EARLYLC, NSNR_START_EARLYLC,
     &   MJDLAST_EARLYLC, MJDLAST_SELECT

c parameters parsed from EARLYLC_STRING:
      INTEGER  MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, PHOTMASK_EARLYLC,
     &         NDAYADD_EARLYLC, PHOTMASK_START_EARLYLC
      REAL  SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, SNR_START_EARLYLC
      CHARACTER  FILTERS_EARLYLC*(MXFILT_ALL)

      COMMON / EARLYINP /
     &   MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, NDAYADD_EARLYLC
     &  ,FILTERS_EARLYLC
     &  ,SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, PHOTMASK_EARLYLC
     &  ,PHOTMASK_START_EARLYLC, SNR_START_EARLYLC


C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


c local

      INTEGER iep, ifilt, ipar, i, NEP_RESET, igal

c ------------- BEGIN -------------

      FOUND_SURVEY = .FALSE.

      SNLC_CID    = -9
      SNLC_CCID   = ''
      SNLC_IAUC   = 'NULL'   ! Aug 31 2017 (can't write blank to FITS file)

      NSPECTRUM   = 0    ! for reading spectra for plot-table
      NLAMBIN_READ = 0

      ISNLC_NEWMJD_HEAD   =  0
      ISNLC_NEWMJD_FOUND  =  0
      ISNLC_NEWMJD_STORE  =  0
      ISNLC_NEWMJD_CUTS   =  0
      ISNLC_NMJD_INCLUDE  =  0 ! Aug 2015
      ISNLC_NEPOCH_FOUND  =  0
      ISNLC_NEPOCH_STORE  =  0
      ISNLC_NEPOCH_PHOTPROB = 0  ! NEPOCH with PHOTPROB >= 0
      ISNLC_NFILT_SNRMAX  =  0
      ISNLC_NFILT_SNRMAX2 =  0
      ISNLC_NFIELD_OVP    =  0

      ISNLC_NFILT_TRESTMIN =  0
      ISNLC_NFILT_TRESTMAX =  0
      ISNLC_NFILT_TREST2   =  0

      ISNLC_NEPOCH_DETECT    =  0
      SNLC_TLIVE_DETECT      = -9.0
      SNLC8_MJD_TRIGGER      = -99.0
      SNLC8_MJD_DETECT_FIRST = -99.0
      SNLC8_MJD_DETECT_LAST  = -99.0

      NEPOCH_BADPHOT      =   0
      ISNLC_FAKE          =   0  ! Feb 2021: default is real data
      ISNLC_CCDNUM(1)     =  -9
      ISNLC_IMGNUM(1)     =  -9

      SNLC8_RA            =  -9.0
      SNLC8_DEC           =  -9.0

      SNLC_ZHELIO        =  -9.0
      SNLC_ZHELIO_ERR    =   0.0
      SNLC_ZCMB          =  -9.0
      SNLC_ZCMB_ERR      =   0.0
      SNLC_ZSN           =  -9.0
      SNLC_ZSN_ERR       =   0.0
      SNLC_REDSHIFT      =  -9.0
      SNLC_REDSHIFT_ERR  =   0.0
      SNLC_VPEC          =   0.0
      SNLC_VPEC_ERR      =   0.0
      ISNLC_zFLAG        =  -999

      SNLC_PIXSIZE       =  -9.0
      SNLC_NXPIX         =  -9.0
      SNLC_NYPIX         =  -9.0

      SNLC_MWEBV         =   0.0
      SNLC_MWEBV_ERR     =   0.0
      SNLC_SEARCH_PEAKMJD    =  -9.0
      SNLC_SNANAFIT_PEAKMJD = -9.0
      ISNLC_TYPE         =  0

      SNLC_PHOTPROB_MIN = 1.0

      SNLC_AREAFRAC_AVG = -9.0

c init a few SNHOST arrays

      SNHOST_NMATCH            =  0
      SNHOST_NMATCH2           =  0
      SNHOST_CONFUSION         = -9.0
      do igal = 1, MXSNHOST
         SNHOST_FLAG(igal)        = 0
         SNHOST_OBJID(igal)       = -9
        DSNHOST_OBJID(igal)       = -9.0
         SNHOST8_RA(igal)         = -999.0
         SNHOST8_DEC(igal)        = -999.0
         SNHOST_ANGSEP(igal)      = -9.0
         SNHOST_DDLR(igal)        = -9.0
         SNHOST_ZPHOT(igal)       = -9.0
         SNHOST_ZPHOT_ERR(igal)   = -9.0
         SNHOST_ZSPEC(igal)       = -9.0
         SNHOST_ZSPEC_ERR(igal)   = -9.0

         SNHOST_LOGMASS(igal)       = -9999.0
         SNHOST_LOGMASS_ERR(igal)   = -9999.0
         SNHOST_LOGSFR(igal)        = -9999.0
         SNHOST_LOGSFR_ERR(igal)    = -9999.0
         SNHOST_LOGsSFR(igal)       = -9999.0
         SNHOST_LOGsSFR_ERR(igal)   = -9999.0
         SNHOST_COLOR(igal)         = -9999.0
         SNHOST_COLOR_ERR(igal)     = -9999.0
      enddo
c --------

      SNLC_SNRMAX_FILT(0) = -9.

      DO ifilt = 1, MXFILT_OBS
         ISNLC_NEPOCH_FILT(ifilt)    =   0
         ISNLC_NEPOCH_PRESN(ifilt)   =  -9
         EXIST_FILT(ifilt)          = .FALSE.
         SNLC_FLUXCALMAX(ifilt)     = -9.
         SNLC_FLUXCALMAX_ERR(ifilt) = -9.
         SNLC_MWXT_MAG(ifilt)       = 0.0
         SNLC_MWXT_MAGERR(ifilt)    = 0.0
         SNLC_MWXT_FLUXFRAC(ifilt)  = 0.0

         SNHOST_SBFLUXCAL(ifilt)      = -999.9
         SNHOST_SBFLUXCAL_ERR(ifilt)  = -999.9
         SNHOST_SBMAG(ifilt)          = -999.9
         do igal = 1, MXSNHOST
            SNHOST_MAGOBS(ifilt,igal)         = +99.0
            SNHOST_MAGOBS_ERR(ifilt,igal)     = +99.0
         enddo
         SNLC_SNRMAX_FILT(ifilt)     = -9.
         SNLC_SNRMAX_SORT(ifilt)     = -9.
         SNLC_FLUXCAL_OFF(ifilt)     = 0.0

         SNLC_FIELDLIST = 'VOID'

         DO ipar = 1, NPAR_ANYLC
           SNLC_SNANAFIT_PEAKMJD_FITPAR(ifilt,ipar) = -99.0
           SNLC_SNANAFIT_PEAKMJD_FITERR(ifilt,ipar) = -99.0
         ENDDO

         SIM_TEMPLATEMAG(ifilt) = 99.0
         SIM_LCWIDTH(ifilt)     = 0.0
      ENDDO

      LSIM_TRUE_SNIa  = .FALSE.
      SIM_MODEL_INDEX = -9
      SIM_COLORPAR    = -9.
      SIM_COLORLAW    = -9.
      SIM_DLMAG       = -9.
      SIM_LENSDMU     = -9.

      SIM_WGT_POPULATION = 1.0
      SIM_SHAPEPAR    = -9.
      SIM_SHAPELAW    = -9.
      SIM_COLORPAR    = -9.
      SIM_COLORLAW    = -9.
      SIM_SALT2x0     = -9.
      SIM_SALT2mb     = -9.
      SIM_AV          = -9.    ! July 2016
      SIM_RV          = -9.    ! idem
      SIM_TEMPLATE_INDEX    = -9
      SIM_SEARCHEFF_MASK = 0
      SIM_MAGSMEAR_COH   = 0.0
      SIM_SALT2gammaDM   = 0.0

      SIM_NGEN_LIBID = 0
      SIM_NOBS_UNDEFINED  = 0
      SIM_SUBSAMPLE_INDEX = -9

      IF ( NCALL_SNANA_DRIVER < 2 ) then
         NEP_RESET = MXEPOCH
      ELSE
         NEP_RESET = ISNLC_NEPOCH_STORE
      ENDIF
c      print*,' xxx NCALL,NEP_RESET=', NCALL_SNANA_DRIVER, NEP_RESET

      DO iep = 1, NEP_RESET

        SNLC_FIELD(iep) = 'VOID'   ! avoid pandas issues with NULL

        ISNLC_NFILT_NEWMJD(iep)          =  0
        ISNLC_EPOCH_RANGE_NEWMJD(1,iep)  =  -9
        ISNLC_EPOCH_RANGE_NEWMJD(2,iep)  =  -9
        ISNLC_IFILT_OBS(iep)      =  -9

        ISNLC_IDFIELD(iep)        =  -9

        SNLC8_MJD(iep)           =  -9.0

        ISNLC_PHOTFLAG(iep)  = 0
        SNLC_PHOTPROB(iep)   = 0.0

        SNLC_SKYSIG(iep)     = 0.0
        SNLC_SKYSIG_T(iep)   = 0.0  ! Mar 2018
        SNLC_PSF_SIG1(iep)   = 0.0
        SNLC_PSF_SIG2(iep)   = 0.0
        SNLC_PSF_RATIO(iep)  = 0.0
        SNLC_PSF_NEA(iep)    = 0.0
        SNLC_GAIN(iep)       = 0.0
        SNLC_RDNOISE(iep)    = 0.0

        SNLC_FLUX_NSIG(iep)       =  0.0
        SNLC_FLUXCAL_ERRCALC(iep) =  0.0
        SNLC_FLUXCAL_ERRTEST(iep) = -9.0
        SNLC_FLUXCAL_HOSTERRCALC(iep) = 0.0
        SNLC_FLUXCAL(iep)         =  0.0
        SNLC_FLUXCAL_ERRTOT(iep)  = -9.0  ! Oct 8 2014
        SNLC_MAG(iep)             =  0.0
        SNLC_MAG_ERRPLUS(iep)     =  0.0
        SNLC_MAG_ERRMINUS(iep)    =  0.0

        SNLC_ZEROPT(iep)          =  0.0
        SNLC_ZEROPT_ERR(iep)      =  0.0

        SNLC_XPIX(iep) = -9.0
        SNLC_YPIX(iep) = -9.0

        SNLC_DTOBS(iep)          = -9.0
        SNLC_DTOBS_SAMEFILT(iep) = -9.0

        SNLC_AREAFRAC(iep)  = -9.0

      END DO  ! end of epoch loop

c zero out the FITVAL_STORE array if fit-option is chosen

      IF ( DO_FIT ) THEN

         do i = 1, 4
           FITCHI2_STORE(i)      = 0.0
           FITPROBCHI2_STORE(i)  = 0.0
           LCCHI2_STORE(i)       = 0.0
           LCPROBCHI2_STORE(i)   = 0.0

           NDOF_STORE(i)  = 0
         enddo

         NDOF_PRIOR = 0

         do ipar = 1, MXFITSTORE
            FITVAL_STORE(ipar) = 0.0
            FITERR_STORE(ipar) = 0.0

            LCVAL_STORE(ipar) = 0.0
            LCERR_STORE(ipar) = 0.0
            LCFRACERRDIF_STORE(ipar) = 0.0
         enddo
      ENDIF


      DO i   = 1, MXERRTYPE
         NERRTYPE(i) = 0
      ENDDO

      DO i = 1, MXVAR_PRIVATE
        PRIVATE_VALUE(i)    = PRIVATE_NULL
      ENDDO

      LSNCUTS       = .FALSE.
      PASS_PRIVCUTS = .TRUE.
      PASS_SIMCUTS  = .TRUE.
      CUTFLAG_SNANA =  0
      ERRFLAG_FIT   = -9  ! init to no fit

      MADE_LCPLOT = .FALSE.

      NSEASON_TOT      = 0
      NSEASON_ACTIVE    = 0


      ISNLC_CUTFLAG_REQEP    = 1
      ISNLC_CUTFLAG_PRIVATE  = 1
      ISNLC_CUTFLAG_SIMVAR   = 1
      ISNLC_WRMASK_FLUXCOR_SNANA = 0
      ISNLC_RDMASK_FLUXCOR_SNANA = 0

      NOBS_EARLYLC    = 0
      NNIGHT_EARLYLC  = 0
      MJDLAST_EARLYLC = -999.
      MJDLAST_SELECT  = -999.
      NPHOTMASK_START_EARLYLC = 0
      NSNR_START_EARLYLC      = 0

      DO i = 1, NPAR_SIMSED
         SIMSED_PARVAL(i) = -999.0
      ENDDO
      DO i = 1, NPAR_LCLIB
         LCLIB_PARVAL(i) = -999.0
      ENDDO

      RETURN
      END   ! end of INIT_SNLC


C =======================================
CDECK  ID>,  INIT_CUTMASK. 
      SUBROUTINE INIT_CUTMASK ( IERR )
c
c Creatd Jan 31, 2006 by R.Kessler
c Initialize CUTMASK_ALL and CUTWIN_XXX
c
c Jan 4 2021:
c  + remove obsolete logic with !LSIM_SNANA && ibit==CUTBIT_SEARCH
c  + check OPT_SNCID_LIST
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IERR ! (O)  0=> OK
      INTEGER ibit

C -------------- BEGIN -------------------

      IERR = 0  ! init output arg

      if ( NCUTBIT .GE. 64 ) then
         print*,' INIT_CUTBIT FATAL ERROR: NCUTBIT=', NCUTBIT
         print*,' ***** ABORT ***** '
         CALL EXIT(EXIT_ERRCODE)
      endif

      CUTMASK8_SN_ALL    = 0  ! init common block var
      CUTMASK8_MJD_ALL   = 0  ! init common block var

      DO 100 ibit = 1, NCUTBIT
         if ( ibit .LE. CUTBIT_MJD_MARKER ) then
           CUTMASK8_SN_ALL = IBSET ( CUTMASK8_SN_ALL, ibit-1 )
         else
           CUTMASK8_MJD_ALL = IBSET ( CUTMASK8_MJD_ALL, ibit-1 )
         endif
100   CONTINUE


c Jan 2021: check option to require ONLY CID-select.

      if ( BTEST(OPT_SNCID_LIST,0) ) THEN
          CUTMASK8_SN_ALL = 0
          CUTMASK8_SN_ALL = IBSET(CUTMASK8_SN_ALL,CUTBIT_CID-1)
          print*,' '
          print*,'      **** APPLY ONLY CID-SELECT CUT **** '
          print*,' '
          CALL FLUSH(6)
      endif

      print*,' '
      print*,' INIT_CUTMASK: NCUTBIT          = ', NCUTBIT
      print*,' INIT_CUTMASK: CUTMASK8_SN_ALL  = ',CUTMASK8_SN_ALL
      print*,' INIT_CUTMASK: CUTMASK8_MJD_ALL = ',CUTMASK8_MJD_ALL

c - - - - - - - - -  -
c July 11 2020:
c  check option to write list of rejected epochs
c   (e.g., to pass to classifier)

      CALL WRITE_EPOCH_IGNORE_INIT()

      RETURN
      END  ! end INIT_CUTMASK

C =============================================
CDECK  ID>,  WRITE_EPOCH_IGNORE_INIT. 
      SUBROUTINE WRITE_EPOCH_IGNORE_INIT()

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LEN
      REAL*8  CUTWIN_TMP(2)
      CHARACTER CUTMODE*12, CUTVARNAME*20
      EXTERNAL write_epoch_list_init, write_epoch_list_addvar

C ---------- BEGIN --------

      LEN = INDEX(OUT_EPOCH_IGNORE_FILE,' ') - 1
      if ( LEN <= 0 ) RETURN

      CALL write_epoch_list_init(
     &     OUT_EPOCH_IGNORE_FILE(1:LEN)//char(0), LEN+1)

      CUTMODE = 'REJECT' // char(0)
c     start with PHOTFLAG cut
      CUTWIN_TMP(1)  = DBLE(PHOTFLAG_MSKREJ(1))
      CUTWIN_TMP(2)  = -9.0
      CUTVARNAME     = 'PHOTFLAG' // char(0)
      CALL write_epoch_list_addvar(CUTVARNAME, CUTWIN_TMP, CUTMODE,
     &     20, 12)

c next check PHOTPROB
      CUTWIN_TMP(1)  = CUTWIN_PHOTPROB(1)
      CUTWIN_TMP(2)  = CUTWIN_PHOTPROB(2)
      CUTVARNAME     = 'PHOTPROB' // char(0)
      CALL write_epoch_list_addvar(CUTVARNAME, CUTWIN_TMP, CUTMODE,
     &     20, 12)

c zero point
      CUTWIN_TMP(1)  = CUTWIN_ZP(1)
      CUTWIN_TMP(2)  = CUTWIN_ZP(2)
      CUTVARNAME     = 'ZP' // char(0)
      CALL write_epoch_list_addvar(CUTVARNAME, CUTWIN_TMP, CUTMODE,
     &     20, 12)

c PSF
      CUTWIN_TMP(1) = CUTWIN_PSF(1)
      CUTWIN_TMP(2) = CUTWIN_PSF(2)
      CUTVARNAME    = 'PSF' // char(0)
      CALL write_epoch_list_addvar(CUTVARNAME, CUTWIN_TMP, CUTMODE,
     &     20, 12)

c      print*,' '
c      print*,' xxx DEBUG STOP xxx '
c      STOP

      RETURN
      END  ! end WRITE_EPOCH_IGNORE_INIT

C =============================================
CDECK  ID>,  WRITE_EPOCH_IGNORE_EXEC. 
      SUBROUTINE WRITE_EPOCH_IGNORE_EXEC(ep)

      IMPLICIT NONE

      INTEGER ep ! index to process

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER   NVAR, IFILT_OBS
      CHARACTER CCID*(MXCHAR_CCID), BAND*2
      REAL*8  MJD, VALUES(20)
      EXTERNAL write_epoch_list_exec

C -------- BEGIN -----------
      IF ( OUT_EPOCH_IGNORE_FILE .EQ. '' ) RETURN

      NVAR = 0

      IFILT_OBS = ISNLC_IFILT_OBS(ep)
      CCID = SNLC_CCID(1:ISNLC_LENCCID) // char(0)
      MJD  = SNLC8_MJD(ep)
      BAND = FILTDEF_STRING(ifilt_obs:ifilt_obs) // char(0)

      NVAR=NVAR+1;  VALUES(NVAR) = DBLE( ISNLC_PHOTFLAG(ep) )
      NVAR=NVAR+1;  VALUES(NVAR) = DBLE( SNLC_PHOTPROB(ep)  )
      NVAR=NVAR+1;  VALUES(NVAR) = DBLE( SNLC_ZEROPT_forCUT(ep) )
      NVAR=NVAR+1;  VALUES(NVAR) = DBLE( SNLC_PSF_FWHM_ARCSEC(ep) )

      CALL write_epoch_list_exec(CCID, MJD, BAND, VALUES,
     &      MXCHAR_CCID, 2 )

      RETURN
      END  ! end WRITE_EPOCH_IGNORE_EXEC

C =======================================
CDECK  ID>,  INIT_CUTNAMES. 
      SUBROUTINE INIT_CUTNAMES ( IERR )
c
c Creatd Jan 31, 2007 by R.Kessler
c Initialize strings for cut names.
c
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IERR ! (O)  0=> OK
      INTEGER ibit, ifilt, ifilt_obs
      character cflt*1

C -------------- BEGIN -------------------

      IERR = 0  ! init output arg

      do ibit = 1, NCUTBIT
        cutvar_name(ibit)  = 'UNDEFINED:'
      enddo

c hard-wire names of cut variables (maxchar = 28)

      cutvar_name(CUTBIT_CID)          = 'CID:'
      cutvar_name(CUTBIT_SNTYPE)       = 'TYPE:'
      cutvar_name(CUTBIT_RA)           = 'RA:'
      cutvar_name(CUTBIT_DEC)          = 'DEC:'
      cutvar_name(CUTBIT_HOSTSEP)      = 'HOST-SN sep:'
      cutvar_name(CUTBIT_TRESTMIN)     = 'Trestmin:'
      cutvar_name(CUTBIT_TRESTMAX)     = 'Trestmax:'
      cutvar_name(CUTBIT_TRESTRANGE)   = 'TrestRange:'
      cutvar_name(CUTBIT_TGAPMAX)      = 'TGAPmax:'
      cutvar_name(CUTBIT_T0GAPMAX)     = 'T0GAPmax:'
      cutvar_name(CUTBIT_TobsMIN)      = 'TobsMin:'
      cutvar_name(CUTBIT_TobsMAX)      = 'TobsMax:'
      cutvar_name(CUTBIT_PEAKMJD)      = 'PEAKMJD:'
      cutvar_name(CUTBIT_NMJD_INCLUDE) = 'NMJD_INCLUDE:'
      cutvar_name(CUTBIT_Nepoch)       = 'Nepoch:'
      cutvar_name(CUTBIT_REDSHIFT)     = 'Redshift:'
      cutvar_name(CUTBIT_REDSHIFT_ERR) = 'Redshift-ERROR:'
      cutvar_name(CUTBIT_PSF)          = 'PSF:'
      cutvar_name(CUTBIT_ZP)           = 'ZP:'
      cutvar_name(CUTBIT_ZPERR)        = 'ZPERR:'
      cutvar_name(CUTBIT_PHOTPROB)     = 'PHOTPROB:'
      cutvar_name(CUTBIT_MWEBV)        = 'MWEBV:'
      cutvar_name(CUTBIT_NSEASON_ACTIVE) = 'NSEASON_ACTIVE:'
      cutvar_name(CUTBIT_REQEP)        = 'REQEP_CUTFLAG:'
      cutvar_name(CUTBIT_PRIVATE)      = 'PRIVATEVAR_CUTS:'
      cutvar_name(CUTBIT_SIMVAR)       = 'SIMVAR_CUTS:'
      cutvar_name(CUTBIT_TREST)        = 'Trest:'
      cutvar_name(CUTBIT_TOBS)         = 'Tobs:'
      cutvar_name(CUTBIT_ERRTEST)      = 'ERR(CALC)/ERR(TRUE):'
      cutvar_name(CUTBIT_SIMPULL)      = '(F-Ftrue)/sigF:'
      cutvar_name(CUTBIT_TREST_TRUEFLUX2) = 'Trest_TRUEFLUX:'
      cutvar_name(CUTBIT_SNRMAX)       = 'SNRmax:'
      cutvar_name(CUTBIT_SNRMAX2)      = 'SNRmax2:'
      cutvar_name(CUTBIT_NFILT_SNRMAX) = 'NFILT_SNRmax:'
      cutvar_name(CUTBIT_NFILT_SNRMAX2)= 'NFILT_SNRmax2:'
      cutvar_name(CUTBIT_NFILT_TRESTMIN) = 'NFILT_Trestmin:'
      cutvar_name(CUTBIT_NFILT_TRESTMAX) = 'NFILT_Trestmax:'
      cutvar_name(CUTBIT_NFILT_TREST2)   = 'NFILT_Trest2:'
      cutvar_name(CUTBIT_NFIELD)         = 'NFIELD:'
      cutvar_name(CUTBIT_SEARCH)         = 'SEARCHEFF_MASK:'

      DO ifilt      = 1, NFILT_SNRMAX
          ifilt_obs = IFILT_SNRMAX(ifilt)
          cflt      = FILTDEF_STRING(ifilt_obs:ifilt_obs)
          ibit = CUTBIT_OFFSET_SNRMAX + ifilt
          cutvar_name(ibit)  = 'SNRMAX-' // cflt // ':'
      ENDDO

      DO ifilt      = 1, NFILT_HOST_SBFLUX  ! Aug 2021
          ifilt_obs = ifilt_HOST_SBFLUX(ifilt)
          cflt      = FILTDEF_STRING(ifilt_obs:ifilt_obs)
          ibit      = CUTBIT_OFFSET_SBFLUX + ifilt
          cutvar_name(ibit)  = 'SBFLUX-' // cflt // ':'
      ENDDO

      RETURN
      END   ! end INIT_CUTNAMES

C ======================================
CDECK  ID>,  MWEBV_FLUXCOR. 
      SUBROUTINE MWEBV_FLUXCOR()
c
c Compute MW extinction in each defined passband,
c and correct SNLC_FLUXCAL[_ERRTOT]
c
c May 7, 2012:
c   Apply  USE_MWCOR log here so that the following arrays
c   are always filled:
c     SNLC_MWXT_[MAG,MAGERR,FLUXFRAC]
c
c May 17, 2012: pass ISN as argument and remove local ISN loop.
c May 21, 2012: remove unused ISN arg.
c Sep 18, 2013: use OPT_MWCOLORLAW as last arg to GALextinct
c
c --------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

c local var

      INTEGER IFILT, IFILT_OBS, NEWMJD, EPMIN, EPMAX, ep, OPT

      REAL*8
     &   XTMW8,  XTMW8_PLUSERR
     &  ,AVMW8,  AVMW8_PLUSERR
     &  ,MWEBV8, MWEBV8_PLUSERR
     &  ,LAM8, GALextinct, RV8

      REAL    XTMW_cor, arg
      CHARACTER CFILT*2

      LOGICAL LDMP

C ------------ BEGIN -------------

      LDMP = .FALSE.

      IF ( USESIM_TRUEFLUX .and. LSIM_SNANA ) THEN
         SNLC_MWEBV     = SIM_MWEBV
         SNLC_MWEBV_ERR = 0.0
      ENDIF


c determin MW extinction in each passband

       MWEBV8          = DBLE(SNLC_MWEBV )
       MWEBV8_PLUSERR  = DBLE(SNLC_MWEBV+SNLC_MWEBV_ERR)

       RV8             = DBLE(RV_MWCOLORLAW)
       AVMW8           = RV8 * MWEBV8
       AVMW8_PLUSERR   = RV8 * MWEBV8_PLUSERR

       OPT = OPT_MWCOLORLAW  ! RK : 9/18/2013

       if (  LDMP ) THEN
          write(6,122) SNLC_CCID(1:ISNLC_LENCCID),
     &       SURVEY_FILTERS(1:NFILTDEF_SURVEY), MWEBV8, OPT
122       format(T5,'xxx --- XTMW(',A,'-', A,') for MWEBV=',F5.3,
     &         2x,'OPT=',I3 )
       endif


      DO ifilt = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          LAM8      = DBLE ( FILTOBS_LAMAVG(ifilt_obs) )

          XTMW8     =
     &           GALextinct ( RV8, AVMW8, LAM8, OPT );
          XTMW8_PLUSERR  =
     &           GALextinct ( RV8, AVMW8_PLUSERR, LAM8, OPT );

          SNLC_MWXT_MAG(ifilt)    = SNGL(XTMW8)
          SNLC_MWXT_MAGERR(ifilt) = SNGL(XTMW8_PLUSERR-XTMW8)

          if ( LDMP ) then
            CFILT = FILTDEF_STRING(ifilt_obs:ifilt_obs)
            write(6,123) CFILT, LAM8, XTMW8
123         format(T5,'xxx ', A,' : <LAM>=',F7.0, 2x, 'XTMW=',F6.4)
            call flush(6)
          endif

c store extinction in flux-fraction units.
c FLUXFRAC = Flux(Extincted)/flux(top-of-Galaxy)
          arg = SNGL(-0.4 * XTMW8)
          SNLC_MWXT_FLUXFRAC(ifilt) = 10.0**arg  ! <= 1.0

      END DO  ! end of ifilt loop


c correct data fluxes if USE_MWCOR=T
      IF ( .NOT.  USE_MWCOR )  RETURN

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE

          EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
          EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

          DO EP = EPMIN, EPMAX

            IFILT_OBS = ISNLC_IFILT_OBS(ep)
            IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
            XTMW_cor  = 1.0 - SNLC_MWXT_FLUXFRAC(ifilt)

            SNLC_FLUXCAL(ep) =
     &      SNLC_FLUXCAL(ep) / XTMW_cor

            SNLC_FLUXCAL_ERRTOT(ep) =
     &      SNLC_FLUXCAL_ERRTOT(ep) / XTMW_cor

          ENDDO

200   CONTINUE  ! NEWMJD

      RETURN
      END   ! end MWEBV_FLUXCOR

C ===========================================
CDECK  ID>,  RDFILE_USRTAGS. 
      SUBROUTINE RDFILE_USERTAGS()
c
c Created Aug 2011 by R.Kessler
c If namelist USERTAGS_FILE is set, then read integer tag
c for each SN specified. These tags are then included in
c analysis ntuples and fitres files. Motivation is to
c easily tag subsets such as SN confirmed from a particular
c telescope.  For SN not listed in the USERTAGS_FILE,
c the tag is automatically set to zero.
c
c If an unknown CCID is found in the USERTAGS_FILE,
c it is ignored (i.e., no abort)
c
c The format of the user-tag file is
c
c  SN:  <CID1>  <TAG-VALUE1>
c  SN:  <CID2>  <TAG-VALUE2>
c  SN:  <CID3>  <TAG-VALUE3>
c  etc ...
c
c --------------------

      IMPLICIT NONE



C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,USRTAGCM. inserted below by ypatchy. 

      INTEGER MXUSERTAG
      PARAMETER ( MXUSERTAG = 1000 ) ! max number of user tags

      INTEGER
     &   N_USERTAGS           ! number of tags in USERTAGS_FILE
     &  ,USERTAG_VALUELIST(MXUSERTAG)  ! list of user tags
     &  ,USERTAG                   ! USERTAG value  for current SN

      BYTE
     &   USERTAG_USED(MXUSERTAG)   ! mark when each USERTAG is used

      CHARACTER
     &   USERTAG_CCIDLIST(MXUSERTAG)*(MXCHAR_CCID)  ! list of CCID

      COMMON / USERTAGCOM /
     &   N_USERTAGS, USERTAG_VALUELIST, USERTAG_CCIDLIST
     &  ,USERTAG, USERTAG_USED



      INTEGER LEN, ITAG, iwd, NWD, N
      CHARACTER
     &   CWD*60
     &  ,CKEY*(MXCHAR_CCID)
     &  ,CCID*(MXCHAR_CCID)
     &  ,NAME_ForC*(MXCHAR_FILENAME)
     &  ,FNAM*30

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------- BEGIN ----------------

      N_USERTAGS    = 0

      IF ( USERTAGS_FILE .EQ. ' ' ) RETURN

      FNAM = 'RDFILE_USERTAGS'

      LEN = INDEX(USERTAGS_FILE,' ') - 1

c init all tags to zero
      DO itag = 1, MXUSERTAG
        USERTAG_VALUELIST(itag) = 0
        USERTAG_CCIDLIST(itag)  = ''
        USERTAG_USED(itag)      = 0
      ENDDO

      CALL PRBANNER("RDFILE_USERTAGS")
      print*,'  Read user tags to identify subsets. '

      NAME_ForC = USERTAGS_FILE(1:LEN)//char(0)
      NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_FILE,NAME_forC,
     &          FNAM//char(0), LEN, 30 )

      DO 100 iwd = 1, NWD-1

         CALL get_PARSE_WORD_fortran(iwd+0,CWD,LEN)
         CKEY = CWD(1:MXCHAR_CCID)

         if ( CKEY .EQ. 'SN:' ) then

           N_USERTAGS = N_USERTAGS + 1
           N = N_USERTAGS

           if ( N .GT. MXUSERTAG ) then
             write(c1err,61) MXUSERTAG
61           format('Number of USER TAGS exceeds bound of ',I5)
             c2err = 'Check ' // USERTAGS_FILE(1:60)
             CALL MADABORT("RDFILE_USERTAGS", c1err, c2err )
           endif

           CALL get_PARSE_WORD_fortran(iwd+1,CWD,LEN)
           READ ( CWD, *) CCID

           CALL get_PARSE_WORD_fortran(iwd+2,CWD,LEN)
           READ ( CWD, *) ITAG

           USERTAG_CCIDLIST(N)  = CCID
           USERTAG_VALUELIST(N) = ITAG

         endif

100   CONTINUE

      RETURN
      END


C =========================================
CDECK  ID>,  GTUSERTAG. 
      SUBROUTINE GET_USERTAG(CCID)

c
c Load global USERTAG value for this SN
c
      CHARACTER CCID*(*)

c local var

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,USRTAGCM. inserted below by ypatchy. 

      INTEGER MXUSERTAG
      PARAMETER ( MXUSERTAG = 1000 ) ! max number of user tags

      INTEGER
     &   N_USERTAGS           ! number of tags in USERTAGS_FILE
     &  ,USERTAG_VALUELIST(MXUSERTAG)  ! list of user tags
     &  ,USERTAG                   ! USERTAG value  for current SN

      BYTE
     &   USERTAG_USED(MXUSERTAG)   ! mark when each USERTAG is used

      CHARACTER
     &   USERTAG_CCIDLIST(MXUSERTAG)*(MXCHAR_CCID)  ! list of CCID

      COMMON / USERTAGCOM /
     &   N_USERTAGS, USERTAG_VALUELIST, USERTAG_CCIDLIST
     &  ,USERTAG, USERTAG_USED




      INTEGER i, LCCID, LTMP
      CHARACTER CCID_TMP*(MXCHAR_CCID)

c -------------- BEGIN --------------

      USERTAG = -999
      IF ( N_USERTAGS .LE. 0 ) RETURN

      LCCID = INDEX(CCID,' ') - 1
      DO 100 i = 1, N_USERTAGS

         if ( USERTAG_USED(i) .NE. 0 ) GOTO 100

         CCID_TMP = USERTAG_CCIDLIST(i)
         LTMP     = INDEX(CCID_TMP,' ') - 1

         IF ( LTMP          .NE. LCCID             ) GOTO 100
         IF ( CCID(1:LCCID) .NE. CCID_TMP(1:LCCID) ) GOTO 100

         USERTAG = USERTAG_VALUELIST(i)
         USERTAG_USED(i) = 1
         RETURN
100   CONTINUE


      RETURN
      END

C ==================================
CDECK  ID>,  MULTISEASON. 
      SUBROUTINE MULTISEASON(IFLAG)

c Created Oct 2014
c Driver for quick analysis to check for multi-season variability.
c
c May 1 2019: convert GET_MULTISEASON args to double.

      IMPLICIT NONE

      INTEGER IFLAG ! (I)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER NEWMJD, EPMIN, EPMAX, EP, NOBS, iSeason
      INTEGER ITMP_REJECT(MXEPOCH)
      REAL*8  TMP8_MJD(MXEPOCH)
      REAL*8  TMP8_FLUX(MXEPOCH), TMP8_FLUXERR(MXEPOCH)
      REAL*8  OUT_CHI2RED(MXSEASON), OUT_AVGFLUX(MXSEASON)
      REAL*8  OUT_MJDMIN(MXSEASON),  OUT_MJDMAX(MXSEASON)
      REAL   PARLIST(8), CHI2RED, CUTVAL
      CHARACTER CCID_forC*(MXCHAR_CCID)
      LOGICAL USE_TGAP, USE_MASK

c -------------------- BEGIN --------------

      IF ( IFLAG == IFLAG_INI ) THEN

         USE_TGAP = MULTISEASON_TGAP < 1.0E8
         USE_MASK = MULTISEASON_OPTMASK > 0
         if ( .NOT. USE_TGAP ) THEN
            MULTISEASON_OPTMASK = 0
            RETURN
         endif
         if ( .NOT. USE_MASK ) MULTISEASON_OPTMASK = 1

c copy user-analysis parameters to list
         PARLIST(1) = MULTISEASON_OPTMASK
         PARLIST(2) = MULTISEASON_TGAP
         PARLIST(3) = MULTISEASON_NREJECT_OUTLIER

c call to C function in multiseason.c
         CALL INIT_MULTISEASON(PARLIST)

         RETURN
      ENDIF

      if ( MULTISEASON_OPTMASK == 0 ) return

c ------ if we get here then analyze this CID -------

c create local array of MJD, FLUX, FLUXERR that were selected by SNRECON
      NOBS = 0

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        DO 201 EP = EPMIN, EPMAX
           if ( ISNLC_SNRECON_USE(ep) == 0 ) GOTO 201
           NOBS = NOBS + 1
           TMP8_MJD(NOBS)     = SNLC8_MJD(ep)
           TMP8_FLUX(NOBS)    = DBLE( SNLC_FLUXCAL(ep) )
           TMP8_FLUXERR(NOBS) = DBLE( SNLC_FLUXCAL_ERRTOT(ep) )
 201    CONTINUE
 200  CONTINUE


c --------------
      CCID_forC = SNLC_CCID(1:ISNLC_LENCCID) // char(0)
      NOBS      = ISNLC_NEWMJD_STORE

      CALL GET_MULTISEASON(
     &      CCID_forC
     &     ,NOBS, TMP8_MJD, TMP8_FLUX, TMP8_FLUXERR ! (I)
     &     ,ITMP_REJECT         ! (O) mask of reject epochs
     &     ,NSEASON_TOT         ! (O) number of seasons found
     &     ,OUT_CHI2RED         ! (O) reduced chi2 per season
     &     ,OUT_MJDMIN          ! (O) min-MJD for each season
     &     ,OUT_MJDMAX          ! (O) max-MJD for each season
     &     ,OUT_AVGFLUX         ! (O) avg flux for each season
     &     )

c transfer to float globals
      DO iSeason = 1, NSEASON_TOT
         MULTISEASON_CHI2RED(iSeason) = SNGL(OUT_CHI2RED(iSeason))
         MULTISEASON_MJDMIN(iSeason)  = SNGL(OUT_MJDMIN(iSeason))
         MULTISEASON_MJDMAX(iSeason)  = SNGL(OUT_MJDMAX(iSeason))
         MULTISEASON_AVGFLUX(iSeason) = SNGL(OUT_AVGFLUX(iSeason))
      ENDDO

      CUTVAL = MULTISEASON_CHI2RED_ACTIVE
      DO iSeason = 1, NSEASON_TOT
        CHI2RED = MULTISEASON_CHI2RED(iSeason)
        IF ( CHI2RED > CUTVAL ) THEN
           NSEASON_ACTIVE = NSEASON_ACTIVE + 1
        ENDIF
      ENDDO

c ------------------------------------------
c transfer ITMP_REJECT flag to ISNLC_RECON_USE
c so that plots show rejected epochs

      NOBS = 0

      DO 2000 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        DO 2001 EP = EPMIN, EPMAX
           if ( ISNLC_SNRECON_USE(ep) == 0 ) GOTO 2001
           NOBS = NOBS + 1
           if ( ITMP_REJECT(NOBS) == 1 ) then
              ISNLC_SNRECON_USE(ep) = 0
           endif
 2001   CONTINUE
 2000 CONTINUE

      RETURN
      END  ! end of MULTISEASON


C ============================================
CDECK  ID>,  SELECT_EARLYLC. 
      LOGICAL FUNCTION SELECT_EARLYLC(EP)
c
c Created March 2015 by R.Kessler
c Return TRUE if EARLYLC-requirements are satsified.
c Logical AND is applied to each selection defined in
c subroutine PARSE_EARLYLC_STRING().
c
c Note that all epochs BEFORE EARLYLC requirements are accepted;
c epochs are rejected after all of the EARLYLC obs or nights
c are found.
c
c 9/15/2017: implement SNR_START and PHOTMASK_START (see manual)
c
c -------------------

      IMPLICIT NONE

      INTEGER EP    ! (I) epoch to analyze

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,EARLYCOM. inserted below by ypatchy. 

      REAL DT_SAMENIGHT
ccc   PARAMETER (DT_SAMENIGHT = 0.333) ! same night within 1/3 day = 8 hr
      PARAMETER (DT_SAMENIGHT = 0.400) ! same night within 0.4 day

c variables for selecting the early part of a light curve
      INTEGER    NOBS_EARLYLC, NNIGHT_EARLYLC
      INTEGER    NPHOTMASK_START_EARLYLC
      REAL       NSNR_START_EARLYLC
      REAL       MJDLAST_EARLYLC, MJDLAST_SELECT

      COMMON / EARLYCOM /
     &   NOBS_EARLYLC, NNIGHT_EARLYLC,
     &   NPHOTMASK_START_EARLYLC, NSNR_START_EARLYLC,
     &   MJDLAST_EARLYLC, MJDLAST_SELECT

c parameters parsed from EARLYLC_STRING:
      INTEGER  MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, PHOTMASK_EARLYLC,
     &         NDAYADD_EARLYLC, PHOTMASK_START_EARLYLC
      REAL  SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, SNR_START_EARLYLC
      CHARACTER  FILTERS_EARLYLC*(MXFILT_ALL)

      COMMON / EARLYINP /
     &   MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, NDAYADD_EARLYLC
     &  ,FILTERS_EARLYLC
     &  ,SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, PHOTMASK_EARLYLC
     &  ,PHOTMASK_START_EARLYLC, SNR_START_EARLYLC


C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      REAL SNR, PROB, MJD
      INTEGER IFILT_OBS, MASK, OVPMASK, OVPMASK_START, NMJD_DIF
      LOGICAL LCUTS, LSNR, LPHOTPROB, LPHOTMASK, LFILT
      LOGICAL LDMP, SAMENIGHT, LNOSEL
      CHARACTER CFILT*2

C --------------- BEGIN --------------

      SELECT_EARLYLC = .TRUE.
      IF ( EARLYLC_STRING .EQ. '' ) RETURN

c strip off info for this epoch.
      IFILT_OBS = ISNLC_IFILT_OBS(ep)
      CFILT     = FILTDEF_STRING(ifilt_obs:ifilt_obs)
      PROB      = SNLC_PHOTPROB(ep)
      MASK      = ISNLC_PHOTFLAG(ep)
      MJD       = SNGL( SNLC8_MJD(ep) )

      if ( SNLC_FLUXCAL_ERRTOT(ep) > 0 ) then
         SNR  = SNLC_FLUXCAL(ep) / SNLC_FLUXCAL_ERRTOT(ep)
         if ( SNR > SNR_START_EARLYLC ) then
            NSNR_START_EARLYLC = NSNR_START_EARLYLC + 1
         endif
      else
         SNR = 0.0
      endif

      IF ( PHOTMASK_EARLYLC .NE. 0 ) THEN
        OVPMASK = IAND(PHOTMASK_EARLYLC,MASK)
      ELSE
        OVPMASK = 999  ! any number > 0
      ENDIF

c check PHOTMASK_START required to start counting epochs (9/15/2017)
c --> ignore epochs before PHOTMASK_START is satisfied.
      IF ( PHOTMASK_START_EARLYLC > 0 ) THEN
        OVPMASK_START = IAND(PHOTMASK_START_EARLYLC,MASK)
      ELSE
        OVPMASK_START = 999  ! any number > 0
      ENDIF

      IF ( OVPMASK_START > 0 ) THEN
         NPHOTMASK_START_EARLYLC = NPHOTMASK_START_EARLYLC + 1
      ENDIF

c set cut-logicals.
      LFILT      = (INDEX(FILTERS_EARLYLC,CFILT(1:1)) > 0)

      LSNR       = (SNR .GE. SNRMIN_EARLYLC) .AND.
     &             (NSNR_START_EARLYLC>0)

      LPHOTPROB  = PROB .GE. PHOTPROBMIN_EARLYLC

      LPHOTMASK  = ( OVPMASK > 0) .AND.
     &             ( NPHOTMASK_START_EARLYLC > 0)

      SAMENIGHT  = ( (MJD-MJDLAST_EARLYLC) < DT_SAMENIGHT )

      LCUTS = (LFILT .and. LSNR .and. LPHOTPROB .and. LPHOTMASK )


c apply all cuts to increment number of early obs.
      IF ( LCUTS ) THEN
         NOBS_EARLYLC = NOBS_EARLYLC + 1
         if ( .NOT. SAMENIGHT ) then
            NNIGHT_EARLYLC = NNIGHT_EARLYLC + 1
            MJDLAST_EARLYLC = MJD
         endif
      ENDIF

c ---------------------------------------------------
c check if we reached max number of OBS or NIGHTS

      IF( NOBS_EARLYLC > MAXOBS_EARLYLC ) THEN
         SELECT_EARLYLC = .FALSE.
      ENDIF

      IF ( NNIGHT_EARLYLC > MAXNIGHT_EARLYLC ) THEN
         SELECT_EARLYLC = .FALSE.
      ENDIF

      IF ( SELECT_EARLYLC ) MJDLAST_SELECT = MJD


c check NDAYADD option to add number of days instead of
c number of obs or nights.

      LNOSEL = (.NOT. SELECT_EARLYLC) .and. (NDAYADD_EARLYLC>0)
      NMJD_DIF = -9
      if ( LNOSEL .and. MJDLAST_SELECT > 10000 ) then
         NMJD_DIF = int(MJD - MJDLAST_SELECT+0.5)
         SELECT_EARLYLC = (NMJD_DIF < NDAYADD_EARLYLC)
      endif

c xxxxxxxxxxxxxxx
c      print*,' xxx LNOSEL=',LNOSEL,
c     &   '  MJD,MJDLAST_SELECT=', MJD,MJDLAST_SELECT
c      print*,' xxx --> NMJD_DIF=', NMJD_DIF,
c     &     '   SELECT=', SELECT_EARLYLC
c xxxxxxxxxxxxxxx

      LDMP = .false.  ! (PROB < 1.0E9)
      if ( LDMP ) THEN
         print*,' xxx ------------------------------------- '
         write(6,666) EP, CFILT, LFILT,
     &           MJD-56000, PROB, NOBS_EARLYLC, NNIGHT_EARLYLC
666      format(' xxx EP=',I3'-',A1, '(',L1,')', 2x,
     &         'MJD=',F7.2, 2x, 'PROB=',F5.2, 2x,
     &         'N[OBS,NITE]=',2I3 )

         print*,' xxx NPHOTMASK_START_EARLYLC = ',
     &       NPHOTMASK_START_EARLYLC

         write(6,667) LFILT, LSNR, LPHOTPROB, LPHOTMASK
667      format(' xxx LCUT(FILT,SNR,PHOTPROB,PHOTMASK) = ',4L3)
         print*,' xxx LCUTS, SELECT = ', LCUTS, SELECT_EARLYLC
      endif

      RETURN
      END     ! SELECT_EARLYLC

C ========================================
CDECK  ID>,  PARSE_EARLYLC. 
      SUBROUTINE PARSE_EARLYLC_STRING()

C Mar 2015 -
c  parse &SNLCINP input EARLYLC_STRING and set global
c  variables in common EARLYCOM.
c  Also print summary to stdout.
c
c Valid keys contained in the EARLYLC_STRING are
c (with example values):
c   MAXOBS:            4        ! default = 999
c   MAXNIGHT:          4        ! default = 999
c   FILTERS:         riz      ! default = all bands
c   SNRMIN:          5.0      ! default = -999
c   PHOTPROBMIN:     0.5      ! default = -999
c   PHOTMASK        4096      ! default =  0
c   NDAYADD           10      ! default =  0
c   PHOTMASK_START  4096      ! default =  0    (disabled)
c   SNR_START          5      ! default =  999  (disabled)
c
c 9/15/2017: check for PHOTMASK_START
c

c -------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,EARLYCOM. inserted below by ypatchy. 

      REAL DT_SAMENIGHT
ccc   PARAMETER (DT_SAMENIGHT = 0.333) ! same night within 1/3 day = 8 hr
      PARAMETER (DT_SAMENIGHT = 0.400) ! same night within 0.4 day

c variables for selecting the early part of a light curve
      INTEGER    NOBS_EARLYLC, NNIGHT_EARLYLC
      INTEGER    NPHOTMASK_START_EARLYLC
      REAL       NSNR_START_EARLYLC
      REAL       MJDLAST_EARLYLC, MJDLAST_SELECT

      COMMON / EARLYCOM /
     &   NOBS_EARLYLC, NNIGHT_EARLYLC,
     &   NPHOTMASK_START_EARLYLC, NSNR_START_EARLYLC,
     &   MJDLAST_EARLYLC, MJDLAST_SELECT

c parameters parsed from EARLYLC_STRING:
      INTEGER  MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, PHOTMASK_EARLYLC,
     &         NDAYADD_EARLYLC, PHOTMASK_START_EARLYLC
      REAL  SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, SNR_START_EARLYLC
      CHARACTER  FILTERS_EARLYLC*(MXFILT_ALL)

      COMMON / EARLYINP /
     &   MAXOBS_EARLYLC, MAXNIGHT_EARLYLC, NDAYADD_EARLYLC
     &  ,FILTERS_EARLYLC
     &  ,SNRMIN_EARLYLC, PHOTPROBMIN_EARLYLC, PHOTMASK_EARLYLC
     &  ,PHOTMASK_START_EARLYLC, SNR_START_EARLYLC


      INTEGER iwd, NWD, NOTUSED, L0, L1, MSKOPT
      CHARACTER
     &   cwd0*(MXCHAR_FILEWORD),
     &   cwd1*(MXCHAR_FILEWORD), FNAM*22
      LOGICAL USEWD(200)

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C -------------- BEGIN -----------------

      FNAM = 'PARSE_EARLYLC_STRING'
      MSKOPT = MSKOPT_PARSE_WORDS_STRING

c set defaults

      NDAYADD_EARLYLC        =  0
      MAXOBS_EARLYLC         =  999
      MAXNIGHT_EARLYLC       =  999
      SNRMIN_EARLYLC         = -999.
      PHOTPROBMIN_EARLYLC    = -999.
      PHOTMASK_EARLYLC       =  0
      PHOTMASK_START_EARLYLC =  0
      NPHOTMASK_START_EARLYLC=  0
      SNR_START_EARLYLC      =  -9999.
      NSNR_START_EARLYLC     =  0
      FILTERS_EARLYLC        = SURVEY_FILTERS

      IF ( EARLYLC_STRING .EQ. '' ) RETURN

      NWD = STORE_PARSE_WORDS(MSKOPT, EARLYLC_STRING//char(0),
     &         FNAM//char(0), 100, 30)

      DO iwd = 1, NWD
         USEWD(iwd) = .FALSE.
      ENDDO

      DO 10 iwd = 1, NWD

          CALL get_PARSE_WORD_fortran(iwd+0, cwd0, L0)
          CALL get_PARSE_WORD_fortran(iwd+1, cwd1, L1)

          if ( cwd0(1:6) .EQ. 'MAXOBS' ) then
             read(cwd1,* ) MAXOBS_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

          if ( cwd0(1:7) .EQ. 'NDAYADD' ) then
             read(cwd1,* ) NDAYADD_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

          if ( cwd0(1:8) .EQ. 'MAXNIGHT' ) then
             read(cwd1,* ) MAXNIGHT_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

          if ( cwd0(1:7) .EQ. 'FILTERS' ) then
             FILTERS_EARLYLC = cwd1
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

          if ( cwd0(1:6) .EQ. 'SNRMIN' ) then
             read(cwd1,* ) SNRMIN_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

          if ( cwd0(1:11) .EQ. 'PHOTPROBMIN' ) then
             read(cwd1,* ) PHOTPROBMIN_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

c   be careful with two keys that have same 'PHOTMASK' in string
          if ( cwd0(1:14) .EQ. 'PHOTMASK_START' ) then
             read(cwd1,* ) PHOTMASK_START_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          else if ( cwd0(1:8) .EQ. 'PHOTMASK' ) then
             read(cwd1,* ) PHOTMASK_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

          if ( cwd0(1:9) .EQ. 'SNR_START' ) then
             read(cwd1,* ) SNR_START_EARLYLC
             USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
          endif

10    CONTINUE

      GLOBAL_BANNER = 'Init Selection of Early Part of Light Curve'
      CALL PRBANNER (GLOBAL_BANNER(1:60) )

      write(6,50) MAXOBS_EARLYLC, MAXNIGHT_EARLYLC
50    format(T5,'Select first ',I2,' obs or ',I2,' nights satisfying:')
      print*,'        FILTER  in   ', FILTERS_EARLYLC(1:40)
      print*,'   and  PHOTPROB > ', PHOTPROBMIN_EARLYLC
      print*,'   and  SNR      > ', SNRMIN_EARLYLC
      print*,'   and  NDAYADD  = ', NDAYADD_EARLYLC

      if ( PHOTMASK_EARLYLC > 0 ) then
         print*,'   and  PHOTFLAG contains ', PHOTMASK_EARLYLC
      endif

      if ( PHOTMASK_START_EARLYLC > 0 ) then
         print*,'   After epoch where PHOTFLAG contains ',
     &         PHOTMASK_START_EARLYLC
      endif

      if ( SNR_START_EARLYLC > -900. ) then
         print*,'   After epoch where SNR > ', SNR_START_EARLYLC
      endif

      print*,' '
      call flush(6)

c ------------------------------------
c if any words are not used --> ABORT !!!

      NOTUSED =  0
      DO 66 iwd = 1, NWD
        if ( .NOT. USEWD(iwd) ) then
            NOTUSED = NOTUSED + 1
            CALL get_PARSE_WORD_fortran(iwd, cwd0, L0)
            write(6,666) cwd0
666         format('ERROR: EARLYLC_STRING contains invalid ', A20)
        endif
66    CONTINUE

      IF ( NOTUSED > 0 ) THEN
        write(c1err,61) NOTUSED
        write(c2err,62) EARLYLC_STRING
61      format('Found ',I2,' undefined words in')
62      format('EARLYLC_STRING="', A48, '"' )
        CALL MADABORT(FNAM,C1ERR,C2ERR)
      ENDIF

      RETURN
      END  ! end of PARSE_EARLYLC_STRING

C ========================================================
CDECK  ID>,  ISTAT_REQUIRE_EPOCHS. 
      INTEGER FUNCTION ISTAT_REQUIRE_EPOCHS()

c Created Sep 2017
c Return 1 (TRUE) if epochs satify user input REQUIRE_EPOCHS_STRING.
c

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,REQEPCOM. inserted below by ypatchy. 
      CHARACTER FILTLIST_REQEP*(MXFILT_ALL)
      INTEGER NFILT_REQEP, IFILTLIST_REQEP(MXFILT_ALL)
      REAL  TRANGE_REQEP(3), SNRMIN_REQEP
      LOGICAL ISFRAME_REST_REQEP, ISFRAME_OBS_REQEP

      COMMON / REQEPINP /
     &    NFILT_REQEP, FILTLIST_REQEP, IFILTLIST_REQEP
     &   ,TRANGE_REQEP, SNRMIN_REQEP
     &   ,ISFRAME_REST_REQEP, ISFRAME_OBS_REQEP

      REAL NDAYS_ABOVE_SNRMIN_REQEP
      COMMON / REQEPCOM / NDAYS_ABOVE_SNRMIN_REQEP



      INTEGER
     &    NEWMJD, EPMIN, EPMAX, EP, i, NOBS(3)

      REAL*8
     &   MJD_FIRST, MJD_LAST, MJD, MJD_DIF
     &  ,MJD_WIN_BEFORE(2), MJD_WIN_AFTER(2)
     &  ,SNR, FLUX, FLUXERR, z1

      CHARACTER FNAM*24
      LOGICAL  LPASS, LTRANGE(3), LDMP

C ------------------- BEGIN ----------------

      FNAM       = 'ISTAT_REQUIRE_EPOCHS'

      ISTAT_REQUIRE_EPOCHS     = 1
      NDAYS_ABOVE_SNRMIN_REQEP = 0.0
      IF ( NFILT_REQEP .EQ. 0 ) RETURN

      MJD_FIRST  = -9.0
      MJD_LAST   = -9.0

      do i = 1, 3
        LTRANGE(i) = .FALSE.
        NOBS(i)    = 0
      ENDDO

      IF ( ISFRAME_OBS_REQEP ) then
         z1   = 1.0
      else
         z1  = 1.0 + SNLC_REDSHIFT
         if ( SNLC_REDSHIFT < 0.0 ) then
            c1err = 'Negative redshift !'
            c2err = 'Cannot compute TREST'
            CALL MADABORT(FNAM, c1err, c2err )
         endif
      endif

C - - - - - - -  - -

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

      DO 201 EP = EPMIN, EPMAX

           MJD      = SNLC8_MJD(EP)
           FLUX     = DBLE( SNLC_FLUXCAL(EP) )
           FLUXERR  = DBLE( SNLC_FLUXCAL_ERRTOT(EP) )
           SNR      = 0.0
           IF ( FLUXERR > 0.00001 ) THEN
              SNR = FLUX / FLUXERR
           ENDIF

           IF ( SNR > SNRMIN_REQEP ) THEN
              if ( MJD_FIRST < 0.0 ) MJD_FIRST = MJD
              MJD_LAST = MJD
              NOBS(2) = NOBS(2) + 1
           ENDIF
201   CONTINUE
200   CONTINUE


c -----------------------------------
c check range of epochs above SNR
      MJD_DIF = MJD_LAST - MJD_FIRST
      NDAYS_ABOVE_SNRMIN_REQEP = SNGL( MJD_DIF/z1 )
      if ( NDAYS_ABOVE_SNRMIN_REQEP > TRANGE_REQEP(2)
     &        .OR. NOBS(2)==0 ) THEN
         ISTAT_REQUIRE_EPOCHS = 0
         GOTO 888
      endif

c We have a short-enough transient.
c Check that there there is at least 1 obs before and after
c the live range, so that a longer-duration event could
c have been observed.

      MJD_WIN_BEFORE(1) = MJD_FIRST - TRANGE_REQEP(1)*z1
      MJD_WIN_BEFORE(2) = MJD_FIRST - 0.001

      MJD_WIN_AFTER(1) = MJD_LAST + 0.001
      MJD_WIN_AFTER(2) = MJD_LAST + TRANGE_REQEP(3)*z1

      DO 400 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
      DO 401 EP = EPMIN, EPMAX

           MJD      = SNLC8_MJD(EP)

           if ( MJD > MJD_WIN_BEFORE(1) .and.
     &          MJD < MJD_WIN_BEFORE(2) ) then
             NOBS(1) = NOBS(1) + 1
           endif

           if ( MJD > MJD_WIN_AFTER(1) .and.
     &          MJD < MJD_WIN_AFTER(2) ) then
             NOBS(3) = NOBS(3) + 1
           endif

401   CONTINUE
400   CONTINUE

c ------------------------------------------------------

      DO i = 1, 3
        if ( NOBS(i)>0 .OR. TRANGE_REQEP(i) < 1.0E-9 ) THEN
           LTRANGE(i) = .TRUE.
        endif
      ENDDO

      LPASS = ( LTRANGE(1) .and. LTRANGE(2) .and. LTRANGE(3) )
      IF ( LPASS ) THEN
         ISTAT_REQUIRE_EPOCHS = 1
      ELSE
         ISTAT_REQUIRE_EPOCHS = 0
      ENDIF

c - - - - - - - - - - -
888   CONTINUE

      LDMP = ( SNLC_CID < -5 )
      IF ( LDMP ) THEN
        print*,' '
        print*,' xxx ---------- DUMP ISTAT_REQUIRE_EPOCHS ------ '
        print*,' xxx CID = ', SNLC_CID
        print*,' xxx TRANGE  = ', TRANGE_REQEP
        print*,' xxx LTRANGE = ', LTRANGE
        print*,' xxx NOBS    = ', NOBS
        print*,' xxx MJD_FIRST/LAST = ',
     &      sngl(MJD_FIRST), '/', sngl(MJD_LAST)
        print*,' xxx ISTAT_REQUIRE_EPOCHS=', ISTAT_REQUIRE_EPOCHS
        print*,' '
      ENDIF

      RETURN
      END   ! end ISTAT_REQUIRE_EPOCHS


C ========================================================
CDECK  ID>,  PARSE_REQUIRE_EPOCHS. 
      SUBROUTINE PARSE_REQUIRE_EPOCHS_STRING()

c Created Sep 2017
c Parse &SNLCINP input REQUIRE_EPOCHS_STRING.
c Main goal is to select fast transients and reject the
c larger source of Supernova.
c
c Example:
c   REQUIRE_EPOCHS_STRING = 'FILTERS riz  TOBS_RANGES  14 20 25 SNRMIN 5'
c   REQUIRE_EPOCHS_STRING = 'FILTERS riz  TREST_RANGES 14 20 25 SNRMIN 5'
c
c Legacy Example:
c    REQUIRE_EPOCHS_STRING = 'gri 14 20 21'
c --> For the gri passbands:
c  + Require (MJD_max - MJD_min)_DETECT < 20 days = [TRANGE(2)]
c  + require NOBS>=1 within 14 days before MJD_min  [TRANGE(1)]
c  + require NOBS>=1 within 21 days after  MJD_max  [TRANGE(3)]
c
c  For TRANGE(2), a "detection" is defined by SNR > CUTWIN_SNRMAX(1).
c  The NOBS>=1 requirements ensure observations before and after
c  the detect-range to avoid edge effects such as a falling
c  light curve at the start of a season where we can't see the
c  entire LC. Such edge cases can be rejected.
c
c  Setting TRANGE(1)=0 or TRANGE(3)=0 will disable the
c  corresponding requirement.
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,REQEPCOM. inserted below by ypatchy. 
      CHARACTER FILTLIST_REQEP*(MXFILT_ALL)
      INTEGER NFILT_REQEP, IFILTLIST_REQEP(MXFILT_ALL)
      REAL  TRANGE_REQEP(3), SNRMIN_REQEP
      LOGICAL ISFRAME_REST_REQEP, ISFRAME_OBS_REQEP

      COMMON / REQEPINP /
     &    NFILT_REQEP, FILTLIST_REQEP, IFILTLIST_REQEP
     &   ,TRANGE_REQEP, SNRMIN_REQEP
     &   ,ISFRAME_REST_REQEP, ISFRAME_OBS_REQEP

      REAL NDAYS_ABOVE_SNRMIN_REQEP
      COMMON / REQEPCOM / NDAYS_ABOVE_SNRMIN_REQEP



      INTEGER ifilt, IFILT_OBS, iwd, NWD, i, L0, L1, MSKOPT
      character FNAM*28, CFILT*2, cwd0*80, cwd1*80
      LOGICAL LEGACY, USEWD(40)

      INTEGER FILTINDX

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C --------------- BEGIN ----------------

      FNAM = 'PARSE_REQUIRE_EPOCHS_STRING'
      MSKOPT = MSKOPT_PARSE_WORDS_STRING

c set defaults
      ISFRAME_REST_REQEP = .FALSE.
      ISFRAME_OBS_REQEP  = .FALSE.
      DO i = 1, 3
        TRANGE_REQEP(i)  = 0.0
      ENDDO
      NFILT_REQEP     = 0
      FILTLIST_REQEP  = ''
      SNRMIN_REQEP    = 0.0   ! defines detection

      IF ( REQUIRE_EPOCHS_STRING .EQ. '' ) RETURN

      NWD = STORE_PARSE_WORDS(MSKOPT,REQUIRE_EPOCHS_STRING//char(0),
     &          FNAM//char(0), 100, 22 )

      LEGACY = ( NWD .EQ. 4 )

      IF ( LEGACY ) THEN
        ISFRAME_OBS_REQEP = .TRUE.
        call get_PARSE_WORD_fortran(1, cwd0, L0)
        read( CWD0,* ) FILTLIST_REQEP

        call get_PARSE_WORD_fortran(2, cwd0, L0)
        read( CWD0,* ) TRANGE_REQEP(1)

        call get_PARSE_WORD_fortran(3, cwd0, L0)
        read( CWD0,* ) TRANGE_REQEP(2)

        call get_PARSE_WORD_fortran(4, cwd0, L0)
        read( CWD0,* ) TRANGE_REQEP(3)

        SNRMIN_REQEP = CUTWIN_SNRMAX(1)
      ELSE
         DO iwd = 1, NWD
            USEWD(iwd) = .FALSE.
         ENDDO

         DO 44 iwd = 1, NWD-1

           call get_PARSE_WORD_fortran(iwd+0, cwd0, L0)
           call get_PARSE_WORD_fortran(iwd+1, cwd1, L1)

           if ( cwd0(1:7) .EQ. 'FILTERS' ) then
              read(cwd1,* ) FILTLIST_REQEP
              USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
           else if ( cwd0(1:6) .EQ. 'SNRMIN' ) then
              read(cwd1,* ) SNRMIN_REQEP
              USEWD(iwd) = .TRUE.;  USEWD(iwd+1) = .TRUE.
           else if ( cwd0(1:11) .EQ. 'TOBS_RANGES' ) then
              USEWD(iwd) = .TRUE.;
              ISFRAME_OBS_REQEP = .TRUE.
              do i = 1, 3
                call get_PARSE_WORD_fortran(iwd+i, cwd1, L1)
                read(cwd1,* ) TRANGE_REQEP(i); USEWD(iwd+i)=.TRUE.
              enddo
           else if ( cwd0(1:12) .EQ. 'TREST_RANGES' ) then
              USEWD(iwd) = .TRUE.;
              ISFRAME_REST_REQEP = .TRUE.
              do i = 1, 3
                call get_PARSE_WORD_fortran(iwd+i, cwd1, L1)
                read(cwd1,* ) TRANGE_REQEP(i); USEWD(iwd+i)=.TRUE.
              enddo
           endif

44       CONTINUE
      ENDIF

c ------------------------------------------
c store absolute filter indices in sparse list
      NFILT_REQEP = INDEX(FILTLIST_REQEP,' ') - 1
      DO 10 ifilt=1, NFILT_REQEP
        CFILT = FILTLIST_REQEP(ifilt:ifilt)
        IFILT_OBS = FILTINDX(cfilt // ' ')
        IFILTLIST_REQEP(IFILT) = IFILT_OBS
10    CONTINUE

      CALL PRBANNER(FNAM)
      print*,'   Require Epochs for filters : ',
     &       FILTLIST_REQEP(1:NFILT_REQEP)

      write(6,41) 'Detection Requires SNR  > ', SNRMIN_REQEP
      write(6,42) '(Tlast - Tfirst)_Detect < ', TRANGE_REQEP(2)
      write(6,42) 'Pre-detect  veto range  = ', TRANGE_REQEP(1)
      write(6,42) 'Post-detect veto range  = ', TRANGE_REQEP(3)
      print*,' ISFRAME[OBS,REST] = ',
     &     ISFRAME_OBS_REQEP, ISFRAME_REST_REQEP
41    format(T8,A, F6.1 )
42    format(T8,A, F6.1, ' days' )

      RETURN
      END         ! end PARSE_REQUIRE_EPOCHS_STRING



C ========================================================
CDECK  ID>,  INIT_MAGCOR. 
      SUBROUTINE INIT_MAGCOR(MAGCOR_INFILE)

c Created Dec 7 2016 by R.Kessler
c Read optional list of mag-correction vs. epoch from ASCII file.
c The file syntax is a FITRES-formatted file containing
c    VARNAMES:  ROW  MAGCOR EXTRA1 EXTRA2 ...
c    SN: [CID]-[MJD]-[BAND]  [MAGCOR] [EXTRA1] [EXTRA2]
c    etc ..
c and see snana manual section  "Epoch-Dependent Mag Corrections".
c Here we read only ROW and MAGCOR, and ignore all other variables.
c ROW must be first column, but MAGCOR can be in any column.
c
c If there is a minus sign in front of the file name,
c     MAGCOR_INFILE = '-/BLA/BLA/MAGCOR.DAT'
c then subtract MAGCOR instead of adding.
c
c  NVAR: 2
c  VARNAMES:  ROW  MAGCOR
c  ROW:  [CID]-[MJD]-[BAND]  [MAGCOR]
c  ROW:  [CID]-[MJD]-[BAND]  [MAGCOR]
c   etc ...
c
c Additional columns are allowed, but will be ignored.
c
c Nov 13 2018: pass MAGCOR_INFILE as input argument.
c
c ----------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER MAGCOR_INFILE*(MXCHAR_FILENAME)  ! (I)

      INTEGER LEN1, LEN2, LEN3, OPTMASK_STORE, ISTAT
      CHARACTER
     &     cFILE*(MXCHAR_FILENAME)
     &    ,cTABLE*20, cVARLIST*20, FNAM*12

c functions
      INTEGER  SNTABLE_AUTOSTORE_INIT, EXIST_VARNAME_AUTOSTORE
      EXTERNAL SNTABLE_AUTOSTORE_INIT, EXIST_VARNAME_AUTOSTORE
      INTEGER ISTAT_MAGCOR_ADD

C ------------ BEGIN -------------

      NSTORE_MAGCOR = 0
      NUSE_MAGCOR   = 0
      IF ( MAGCOR_INFILE .EQ. ' '    ) RETURN
      IF ( MAGCOR_INFILE .EQ. 'NULL' ) RETURN
      IF ( MAGCOR_INFILE .EQ. 'NONE' ) RETURN

      SIGN_MAGCOR = +1  ! default is to add
      IF ( MAGCOR_INFILE(1:1) .EQ. '-' ) THEN
         SIGN_MAGCOR = -1  ! subtract instead
         MAGCOR_INFILE = MAGCOR_INFILE(2:)
      ENDIF

      FNAM = 'INIT_MAGCOR'
      CALL PRBANNER('INIT_MAGCOR: read mag-correction vs. epoch')

      CALL ENVreplace(MAGCOR_INFILE)
      LEN1   = INDEX(MAGCOR_INFILE,' ') - 1
      cFILE  = MAGCOR_INFILE(1:LEN1) // char(0)

c check header to see if if MAGCOR has been added in version
c ISTAT=1 if MAGCOR alread added ; ISTAT=0 if not already added.
      ISTAT = ISTAT_MAGCOR_ADD(MAGCOR_INFILE,VERSION_PHOTOMETRY(1))

c avoid double-counting MAGCOR
      IF ( ISTAT==0 .and. SIGN_MAGCOR < 0 ) THEN
         C1ERR = 'MAGCOR not in data fluxes --> '
         C2ERR = 'Will not subtract MAGCOR'
         CALL MADABORT(FNAM,C1ERR,C2ERR)
      ENDIF
      IF ( ISTAT==1 .and. SIGN_MAGCOR > 0 ) THEN
         C1ERR = 'MAGCOR already in data fluxes --> '
         C2ERR = 'Will not double-count MAGCOR.'
         CALL MADABORT(FNAM,C1ERR,C2ERR)
      ENDIF

      cTABLE = 'MAGCOR' // char(0)  ! any table name will work for ASCII
      LEN2   = INDEX(cTABLE,' ') - 1

      cVARLIST = 'MAGCOR' // char(0)
      LEN3     = INDEX(cVARLIST,' ') - 1

      OPTMASK_STORE = 5  ! 1->5 on May 11 2017
      NSTORE_MAGCOR =
     &       SNTABLE_AUTOSTORE_INIT(cFILE, cTABLE, cVARLIST,
     &               OPTMASK_STORE,  LEN1, LEN2, LEN3 )

      write(6,20) NSTORE_MAGCOR
 20   format(/, T4,'Stored ', I6, ' epochs of MAG corrections. ')
      print*,'    Sign of MAGCOR : ', SIGN_MAGCOR
      print*,' '  ;  CALL FLUSH(6)

      RETURN
      END  ! end INIT_MAGCOR


C ========================================
CDECK  ID>,  ISTAT_MAGCOR_ADD. 
      INTEGER FUNCTION ISTAT_MAGCOR_ADD(MAGCOR_FILE,VERSION)

c Check header of MAGCOR_FILE to see if VERSION has MAGCOR
c already added.  CHeck MAGCOR_FILE for
c
c   VERSION_ADD:  <VERSION>
c
c If MAGCOR already added in data files, return 1.
c If MAGCOR not added, return 0
c
c This function is used to help avoid double-counting MAGCOR,
c but the MAGCOR-add process (outside SNANA) must add  the
c VERSION_ADD key at the top of the file.
c
c May 22 2018: skip lines with comment field

      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



c inputs
      CHARACTER MAGCOR_FILE*(*), VERSION*(*)

c local
      INTEGER FOUND_ROW, LUN, NWD, LEN, LENVER, NLINE, MSKOPT
      LOGICAL SAME_LEN, SAME_VER, KEYMATCH
      CHARACTER LINE*200, cwd*80, VERSION_ADD*80, FNAM*22
      CHARACTER C1ERR*72, C2ERR*72

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS
C --------------- BEGIN ---------------

      ISTAT_MAGCOR_ADD = 0 ! init function value
      FNAM   = 'ISTAT_MAGCOR_ADD'
      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      LENVER = INDEX(VERSION,' ' ) - 1

      NLINE=0; FOUND_ROW=0 ; LUN = 24
      OPEN(   UNIT   = LUN
     &      , FILE   = MAGCOR_FILE
     &      , STATUS = 'OLD'
     &           )


c keep reading until first ROW key is found

      DO 200 WHILE ( FOUND_ROW == 0 )
         READ(LUN,100) LINE
 100     format(A160)

         IF ( LINE(1:1) .EQ. '#' ) GOTO 200

         NLINE = NLINE + 1

         if ( NLINE > 50 ) then
            C1ERR = 'Could not find ROW key after 50 lines.'
            C2ERR = 'Check ' // MAGCOR_FILE
            CALL MADABORT(FNAM,C1ERR,C2ERR)
         endif

         NWD = STORE_PARSE_WORDS(MSKOPT, LINE//char(0),
     &            FNAM//char(0), 200, 22)

         if ( NWD < 2 ) goto 200

         CALL get_PARSE_WORD_fortran(1,cwd,LEN)

         IF ( cwd(1:4) .EQ. 'ROW:' ) goto 500

         KEYMATCH = cwd(1:16) .EQ. 'VERSION_ADD:'
         IF ( KEYMATCH ) THEN
            CALL get_PARSE_WORD_fortran(2,VERSION_ADD,LEN)
            SAME_LEN = ( LEN .EQ. LENVER )
            SAME_VER = ( VERSION(1:LEN) .EQ. VERSION_ADD(1:LEN) )
            IF ( SAME_LEN .and. SAME_VER ) THEN
              ISTAT_MAGCOR_ADD = 1
              GOTO 500
            ENDIF
         ENDIF
200   CONTINUE

500   CONTINUE
      CLOSE(UNIT = LUN)

      RETURN
      END

C ========================================================
CDECK  ID>,  EXEC_MAGCOR. 
      SUBROUTINE EXEC_MAGCOR(ep)

c Dec 2016
c Apply MAGCOR read in INIT_MAGCOR. The corrections are
c applied to the FLUXCAL.
c Modify SNLC_FLUXCAL(ep) and SNLC_MAG(ep)
c
c May 1 2017: abort on crazy MAGCOR
c ---------------------------------

      IMPLICIT NONE

      INTEGER ep ! epoch index

c local variables

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFILT_OBS, ISTAT, L, L2
      REAL*8 MJD, DVAL
      REAL*4 MAGCOR, FCOR
      CHARACTER cVARNAME*20, BAND*2, cDUM*20
      CHARACTER STR_EPID1*60, STR_EPID2*60

      REAL MAGCOR_CRAZY
      PARAMETER ( MAGCOR_CRAZY = 0.2 )

c function
      EXTERNAL SNTABLE_AUTOSTORE_READ
c --------------- BEGIN -----------------

      IF ( NSTORE_MAGCOR <= 0 ) RETURN

      IFILT_OBS = ISNLC_IFILT_OBS(ep)
      BAND      = FILTDEF_STRING(ifilt_obs:ifilt_obs)
      MJD       = SNLC8_MJD(ep)

c construct unique epoch-identifier by gluing SNID+MJD+BAND
c into a single string.

      L  = INDEX(SNLC_CCID,' ') - 1
      WRITE(STR_EPID1,40) SNLC_CCID(1:L), MJD, BAND, char(0)
40    FORMAT(A,'-',F9.3,'-', A1, A )

      cVARNAME = 'MAGCOR' // char(0)

      CALL SNTABLE_AUTOSTORE_READ(STR_EPID1, cVARNAME, ISTAT,
     &                 DVAL,cDUM, 60,10,10 )

c if no MAGCOR, then try again with IAUC name
      IF ( ISTAT .NE. 0 ) THEN
        L2  = INDEX(SNLC_IAUC,' ') - 1
        WRITE(STR_EPID2,40) SNLC_IAUC(1:L2), MJD, BAND, char(0)
        CALL SNTABLE_AUTOSTORE_READ(STR_EPID2, cVARNAME, ISTAT,
     &                 DVAL,cDUM, 60,10,10 )
      ENDIF

      IF ( ISTAT .EQ. 0 ) then
        NUSE_MAGCOR  = NUSE_MAGCOR + 1
        MAGCOR = sngl(DVAL) * SIGN_MAGCOR

c trap crazy MAGCOR
        if ( abs(MAGCOR) > MAGCOR_CRAZY ) then
           write(C1ERR,61) MAGCOR
61         format('Crazy MAGCOR = ', G12.4 )
           C2ERR = 'Check ' // STR_EPID1(1:L+12)
           CALL MADABORT("EXEC_MAGCOR",C1ERR,C2ERR)
        endif

        FCOR   = 10**(-0.4*MAGCOR)

        SNLC_FLUXCAL(ep) = SNLC_FLUXCAL(ep) * FCOR
        SNLC_MAG(ep)     = SNLC_MAG(ep) + MAGCOR

c        write(6,66) DVAL, STR_EPID1, ISTAT
c66      format(' xxx MAGCOR=',F6.3,' for ', A20,'  ISTAT=',I3)
c        call flush(6)
      ENDIF

      CALL SETMASK_FLUXCOR_SNANA(MASK_FLUXCOR_SNANA)

      RETURN
      END  ! end EXEC_MAGCOR

C ========================================================
CDECK  ID>,  END_MAGCOR. 
      SUBROUTINE END_MAGCOR()
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
C --------------- BEGIN --------------

      IF ( NSTORE_MAGCOR == 0 ) RETURN

      print*,' '
      print*,' MAGCOR SUMMARY:'
      write(6,20) NUSE_MAGCOR, NSTORE_MAGCOR
20    format(T8,'Used ',I6,' MAGCOR epochs from ',
     &          I6,' read from file.' )

      RETURN
      END


C ========================================================
CDECK  ID>,  RD_VPEC_FILE. 
      SUBROUTINE RD_VPEC_FILE()
c ----------------------------
      IMPLICIT NONE
c local var

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
C ------------- BEGIN ------------
      IF ( VPEC_FILE .EQ. '' ) RETURN
      C1ERR = '&SNLCIP VPEC_FILE input is obsolete'
      C2ERR = 'Use HEADER_OVERRIDE_FILE'
      CALL MADABORT("RD_VPEC_FILE",C1ERR,C2ERR)   ! Jun 8 2020
      RETURN
      END  ! end of RD_VPEC_FILE


C ================================
CDECK  ID>,  ZHD. 
      SUBROUTINE REDSHIFT_HD()

c Created Oct 2013 by R.Kessler.
c Compute redshift 'ZHD' for  Hubble diagram, which is
c ZCMB + vPec correction.
c
c Nov 30 2016:
c  + re-factor to use externally-computed SNLC_VPEC.
c    i.e., move the read-vpec-file stuff into RD_VPEC_FILE.
c
c
c Jan 26 2018: set SNLC_ZPEC[_ERR]
c
c ----------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      LOGICAL  DOCOR_VPEC
      REAL     ZERR1, ZERR2, ZPEC, ZPECERR

C ------------ BEGIN ---------

c init default with ZHD = CMB redshift
      SNLC_ZHD        = SNLC_ZCMB
      SNLC_ZHD_ERR    = SNLC_ZCMB_ERR

      DOCOR_VPEC = .FALSE.
      IF ( SNLC_VPEC     .NE. 0.0 ) DOCOR_VPEC = .TRUE.
      IF ( SNLC_VPEC_ERR .NE. 0.0 ) DOCOR_VPEC = .TRUE.

      SNLC_ZPEC     = SNLC_VPEC     / SNGL(CLIGHT)
      SNLC_ZPEC_ERR = SNLC_VPEC_ERR / SNGL(CLIGHT)

c ------------------------------------------
c re-compute ZHD and its error if SNLC_VPEC has non-null value
c Jan 3 2018: use VPEC (sigma_z) correction from Eq. 1 (A1) in
c             Davis 2012 [https://arxiv.org/pdf/1012.2912.pdf]

      IF ( DOCOR_VPEC ) THEN

         ZPEC     = ( SNLC_VPEC     / SNGL(CLIGHT) )
         ZPECERR  = ( SNLC_VPEC_ERR / SNGL(CLIGHT) )

         if ( RESTORE_WRONG_VPEC ) then
c    use incorrect VPEC convention ... to be deleted someday
            SNLC_ZHD = (1.0+SNLC_ZCMB) * (1.0+ZPEC) - 1.0  ! Jan 2018;
         else
c    use correct VPEC convention
            SNLC_ZHD = (1.0+SNLC_ZCMB) / (1.0+ZPEC) - 1.0  ! Oct 2020
         endif

         ZERR1 = SNLC_ZCMB_ERR
         ZERR2 = ZPECERR * (1.0 + SNLC_ZCMB) ! Eq A1, Davis 2012
         SNLC_ZHD_ERR = sqrt(ZERR1*ZERR1 + ZERR2*ZERR2)
      ENDIF

      RETURN
      END   ! REDSHIFT_HD

C ============================================
CDECK  ID>,  SNRECON. 
      SUBROUTINE SNRECON()
c
c Created Feb 10, 2006 by R.Kessler
c
c Miscellaneous reconstruction/computation of
c useful variables for analysis.
c
c Includes:
c
c  * ISNLC_NFILT_TRESTMIN[MAX]
c  * ISNLC_NFILT_TREST2
c  * SNLC_TREST(epoch)        = MJD - MJDatPEAK(search)
c  * SNLC_TOBS(epoch)
c  *
c  * SNLC_FLUXCAL_ERRCALC(ifilt,epoch,isn)  ! calc flux error
c  * SNHOST_ZPHOT[_ERR]
c  * SNLC_SNRMAX_FILT(ifilt)
c  * SNLC_SNRMAX_SORT(rank)
c  * SNLC_SNRMAX_IFILTDEF(ifilt)
c  * SNLC_FLUXCALMAX(ifilt)
c  * SNLC_FLUXCALMAX_ERR(ifilt)  ! Nov 2022
c
c  * correct SNLC_MAG and FLUXCAL for AB mag-offsets
c
c  * erase filter-epochs with bad photometry flag
c
c
c
c Feb 12 2018: for USE_SNHOST_ZPHOT=T, convert host zphot to host zcmb
c Feb 16 2018: compute SNHOST_SBMAG(ifilt)
c Mar 18 2017: fill SNLC_DTOBS[_SAMEFILT] = time since last obs
c Sep 16 2018: compute NOBS_DETECT and TLIVE_DETECT
c
c Nov 12 2018: check APPLY_FLUXCOR_BUG to apply bug of computing
c              SNRMAX variables before EXEC_FUDGE_FLUXCAL()
c
c Feb 08 2020: apply PSF, ZPERR, PHOTPROB cuts here so that USEFLAG is set.
c Feb 12 2020: check MWEBV_FORCE
c Nov 30 2020: compute SIM_EPCHI2FLUX for SNANA+EPOCHS table
c Feb 9  2022: fix bug setting SUBSURVEY_NAME_LIST
c -------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



c local var

      INTEGER
     &   newmjd, ifilt, ifilt_obs, LENLIST, LENNAME, INDEX_OVP
     &  ,NBAND_SNRMAX, NBAND_SNRMAX2
     &  ,EPMIN, EPMAX, ep, isort, PHOTFLAG
     &  ,ORDER, INDEX_SORT(MXFILT_OBS)  ! SORT args

      REAL
     &   Fluxcal, Fluxcal_err, TRUEFLUX, ERRTEST
     &  ,Xnsig, MAG, SIM_MAG, magoff, ZP, PHOTPROB, TMP
     &  ,Tobs, z1, z, Trest, scale, arg, PSF, ZPERR
     &  ,Zhost, Zhosterr, LAMOBS, LAMZ1,  SNRMAX, SUM_AREAFRAC

      REAL*8  MJD8, EBV8, EBVERR8
      REAL*8  MJD8_LASTALL, MJD8_LASTFILT(MXFILT_ALL)
      REAL*8  MU_OLD, MU_NEW, z8
      LOGICAL
     &   LSIG, LLAM, LZ, LTEST, LXMJD, LINCMJD
     &  ,LPSF, LZPERR, LPP, LERRTEST
     &  ,LSNRMAX(MXFILT_ALL)
     &  ,LSNRMAX2(MXFILT_ALL)
     &  ,LFLUX, LERR, LTMP, USE4SNRMAX

c function
      REAL*8   DLMAG8_REF
      EXTERNAL SORTFLOAT, modify_MWEBV_SFD
      INTEGER  ISTAT_REQUIRE_EPOCHS

C ------------------ BEGIN -----------------

c check to increment SUBSURVEY_LIST
c WARNING: If CFA follows CFA3, the code will think that CFA already exists as a survey
      IF ( IDSURVEY .ne. IDSUBSURVEY ) THEN
        LENNAME = INDEX(SUBSURVEY_NAME,' ') - 1
        INDEX_OVP = INDEX(SUBSURVEY_NAME_LIST,SUBSURVEY_NAME(1:LENNAME))
        IF ( INDEX_OVP<=0 ) THEN
          LENLIST = INDEX(SUBSURVEY_NAME_LIST,' ') - 1
          if ( LENLIST == 0 ) then
             SUBSURVEY_NAME_LIST = SUBSURVEY_NAME
          else
            SUBSURVEY_NAME_LIST = SUBSURVEY_NAME_LIST(1:LENLIST)
     &          // ',' // SUBSURVEY_NAME
          endif
        ENDIF
      ENDIF

c - - - - - - - - -
c prepare redshifts; e.g. use photo-z, apply systematic shifts, etc ...
      CALL SET_REDSHIFTS()

c - - - - -
      Z    = SNLC_REDSHIFT

      if ( Z > 0.0 ) then
         Z1 = 1.0  + z
      else
         Z1 = 1.0  ! in case Z = -9 is undefined; Trest -> Tobs
      endif

      ISNLC_NEPOCH_USE = 0


c ------ compute MJDMIN/MJDMAX here before calling SET_PKMJD ------

      SNLC8_MJDMIN  = 1.0E8
      SNLC8_MJDMAX  = 0.0
      DO NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

        DO EP = EPMIN, EPMAX
          SNLC8_FLUXCAL(EP)        = DBLE(SNLC_FLUXCAL(ep))
          SNLC8_FLUXCAL_ERRTOT(EP) = DBLE(SNLC_FLUXCAL_ERRTOT(ep))
          MJD8  = SNLC8_MJD(EPMIN)
          IF( MJD8 .GT. SNLC8_MJDMAX ) SNLC8_MJDMAX = MJD8
          IF( MJD8 .LT. SNLC8_MJDMIN ) SNLC8_MJDMIN = MJD8
       ENDDO
      ENDDO

c Sep 21 2013: check option to modify MWEBV_SFD;
c Note that MWEBV and MWEBV_ERR are modified if OPT_MWEBV > 0
      EBV8 = DBLE(SNLC_MWEBV) ; EBVERR8 = DBLE(SNLC_MWEBV_ERR)

      CALL modify_MWEBV_SFD(OPT_MWEBV, SNLC8_RA, SNLC8_DEC,
     &                      EBV8, EBVERR8)  ! I -> O

      SNLC_MWEBV     = SNGL(EBV8)     * MWEBV_SCALE + MWEBV_SHIFT
      SNLC_MWEBV_ERR = SNGL(EBVERR8)  * MWEBV_SCALE
      IF ( MWEBV_FORCE > -0.001 ) THEN
         SNLC_MWEBV = MWEBV_FORCE
         SNLC_MWEBV_ERR = 0.0
      ENDIF

c compute Galactic extinction in each band
c (Oct 11 2013: code moved from MAIN to here)
      CALL MWEBV_FLUXCOR()

c determine redshift for Hubble diagram (Oct 2013)
      CALL REDSHIFT_HD()

c get approx peakMJD
      if ( OPT_SETPKMJD > 0 ) THEN
         CALL SET_PEAKMJD()
      endif

      CALL SELECT_EPOCH_DRIVER(2) ! apply Trest cuts

c -----------------------------------------------
c pick host photoZ

      Zhost    = -9.0
      Zhosterr = -9.0

      if ( SNHOST_ZPHOT(1) .GT. 0.0 ) then
         zhost    = SNHOST_ZPHOT(1)
         zhosterr = SNHOST_ZPHOT_ERR(1)
      else
        SNHOST_ZPHOT(1)     = Zhost
        SNHOST_ZPHOT_ERR(1) = Zhosterr
      endif

       CALL SET_SNHOST_CONFUSION()

c compute lumi-distance using "standard" cosmology
c Useful as initial value for fits.

      IF ( Z .GT. 1.0E-5 ) THEN
         z8 = dble(z)
         SNLC_DLMAG  = SNGL(DLMAG8_REF(z8) )
      ELSE
         SNLC_DLMAG  = -9.0  ! undefined
      ENDIF


      do ifilt = 1, NFILTDEF_SURVEY
         LSNRMAX(ifilt)       = .FALSE.
         LSNRMAX2(ifilt)      = .FALSE.
         MJD8_LASTFILT(ifilt) = -9.0
         CALL SET_SBMAG(ifilt)  ! Feb 17 2018: compute SBMAG from SBFLUX
      enddo

      NBAND_SNRMAX  = 0
      NBAND_SNRMAX2 = 0
      MJD8_LASTALL  = -9.0
      NEP_SIM_MAGOBS =  0
      SUM_AREAFRAC   = 0.0

c fill ISNLC_NFIELD with number of fields;
      CALL COUNTFIELDS()

c init computation of PROB_TRUEFLUX
      CALL PROB_TRUEFLUX_CALC(0)

c = = = = = = = = = = = = = = = = = = = = = = = = = = = =
c = = = = = = = = START LOOP OVER EPOCHS = = = = = = = =
c = = = = = = = = = = = = = = = = = = = = = = = = = = = =

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

        MJD8  = SNLC8_MJD(EPMIN)
        Tobs  = SNGL(MJD8) - SNLC_SEARCH_PEAKMJD
        Trest = Tobs / z1

        SNLC_TOBS(EPMIN)  = Tobs
        SNLC_TREST(EPMIN) = Trest

        DO 201 EP = EPMIN, EPMAX

           ISNLC_SNRECON_USE(ep) = 0

           SNLC_TREST(EP) = Trest
           SNLC_TOBS(EP)  = Tobs
           IFILT_OBS = ISNLC_IFILT_OBS(ep)
           IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)

           CALL CHECK_DUPLICATE_MJDBAND(ep) ! Jun 13 2017

c Feb 6 2020: fudge errors here before SNRMAX is computed

           CALL EXEC_FUDGE_FLUXCAL(ep)  ! flux and fluxerr fudges

           CALL SET_MAG(ep)  ! Jan 23 2018

           USE4SNRMAX = LFILTDEF_SNRMAX(ifilt_obs) ! Apr 2014

c test filter mean only if KCOR file is read.
           LLAM = .TRUE.

c Mar 22 2023 restore LLAM test that was mistakenly removed when
c             fortran-KCOR code was replaced with C code.
c
          LZ = ( Z > 0 .and. Z < 998 )
          IF ( LZ .and. EXIST_KCOR_FILE ) THEN
            LAMOBS = FILTOBS_LAMAVG(ifilt_obs)
            LAMZ1  = LAMOBS / Z1
            LLAM   =
     &           LAMZ1  .GE. CUTWIN_LAMREST(1) .and.
     &           LAMZ1  .LE. CUTWIN_LAMREST(2) .and.
     &           LAMOBS .GE. CUTWIN_LAMOBS(1)  .and.
     &           LAMOBS .LE. CUTWIN_LAMOBS(2)
          ENDIF
c
c strip off local variables.
          Fluxcal      = SNLC_FLUXCAL(ep)
          Fluxcal_err  = SNLC_FLUXCAL_ERRTOT(ep)
          mag          = SNLC_MAG(ep)

c Jan 3 2018: skip saturated mags
          if ( FLUXCAL_ERR .GE. 0.9E8 .AND. LSIM_SNANA ) GOTO 201

c convert sim-mag to SIM_FLUXCA
          IF ( ISJOB_SIM ) THEN
             ZP        = ZEROPOINT_FLUXCAL_DEFAULT
             SIM_MAG   = SIM_EPMAGOBS(ep)
             if ( SIM_MAG < 90.0 ) then
               NEP_SIM_MAGOBS = NEP_SIM_MAGOBS + 1 ! Nov 25 2019
               ARG            = 0.4*(ZP - SIM_MAG)
               TRUEFLUX       = 10.0**(ARG)
             else
               TRUEFLUX = 0.0
             endif
             SIM_EPFLUXCAL(ep) = TRUEFLUX
             IF ( USESIM_TRUEFLUX ) SNLC_FLUXCAL(ep)=TRUEFLUX

             TMP  = (TRUEFLUX - FLUXCAL)/ FLUXCAL_ERR
             SIM_EPCHI2FLUX(ep) = TMP * TMP  ! Nov 30 2020
             SIM_EPPULL(ep)     = TMP        ! Mar 16 2021
             CALL PROB_TRUEFLUX_CALC(ep)
          ELSE
             SIM_EPFLUXCAL(ep)  = -9.0
             SIM_EPCHI2FLUX(ep) = -9.0
             SIM_EPPULL(ep)     = -9.0
          ENDIF

          CALL FLUXERRCALC( ep, Fluxcal, Fluxcal_err )

c compute significance.
          Xnsig  = -999.0
          LERR   = (Fluxcal_err > 0.0 )
          LFLUX  = (abs(Fluxcal+9.0) > 1.0E-5 )  !  FLUXCAL != -9
          if ( LERR .and. LFLUX ) then
             Xnsig  = Fluxcal / Fluxcal_err
          endif

c ----------------
c Correct MAG and FLUXCAL  for  MAGOFF_AB.
c This correction is done AFTER Xsig = S/N is calculated

           magoff = MAGOBS_SHIFT_ZP_FILT(ifilt_OBS)
           SNLC_MAG(ep) = SNLC_MAG(ep) + magoff
           FLUXSCALE_ZP_FILT(IFILT_OBS) = 10.0**(-0.4 * magoff)

           if ( magoff .ne. 0.0 ) then
             scale = FLUXSCALE_ZP_FILT(IFILT_OBS)
             SNLC_FLUXCAL(ep) =
     &       SNLC_FLUXCAL(ep) * Scale
             SNLC_FLUXCAL_ERRTOT(ep) =
     &       SNLC_FLUXCAL_ERRTOT(ep) * Scale
           endif


c Mar 2018: store time since last obs: all bands, and same band
          IF ( MJD8_LASTALL > 0.0 ) THEN
             SNLC_DTOBS(ep) = SNGL(MJD8 - MJD8_LASTALL)
          ENDIF
          IF ( MJD8_LASTFILT(ifilt) > 0.0 ) THEN
             SNLC_DTOBS_SAMEFILT(ep) = SNGL(MJD8 - MJD8_LASTFILT(ifilt))
          ENDIF
          MJD8_LASTALL         = MJD8
          MJD8_LASTFILT(ifilt) = MJD8

c ----------------
c signal is accepted if it passes S/noise cut,
c or it is within the Trest window.

          SNLC_FLUX_NSIG(ep) = Xnsig

c check how many obs are in the INCLUDE_MJD window (Aug 2015)
          LINCMJD = MJD8 .GE. CUTWIN_MJD_INCLUDE(1) .and.
     &              MJD8 .LE. CUTWIN_MJD_INCLUDE(2)
          IF ( LINCMJD ) ISNLC_NMJD_INCLUDE = ISNLC_NMJD_INCLUDE + 1

c check MJD-exclude window to reject epochs (but keep LC)
          LXMJD = MJD8 .GE. CUTWIN_MJD_EXCLUDE(1) .and.
     &            MJD8 .LE. CUTWIN_MJD_EXCLUDE(2)

c Feb 2020: check PSF and ZPERR cuts here
          PSF  = SNLC_PSF_FWHM_ARCSEC(EP)
          LPSF = PSF .GE. CUTWIN_PSF(1) .and. PSF.LE.CUTWIN_PSF(2)

          ZPERR  = SNLC_ZEROPT_ERR(EP)
          LZPERR = ZPERR .GE. CUTWIN_ZPERR(1) .and.
     &             ZPERR .LE. CUTWIN_ZPERR(2)

          PHOTPROB = SNLC_PHOTPROB(ep)
          LPP  = (PHOTPROB > CUTWIN_PHOTPROB(1) .OR. PHOTPROB<-0.001)

          ERRTEST = SNLC_FLUXCAL_ERRTEST(ep)
          LERRTEST = ERRTEST .GE. CUTWIN_ERRTEST(1) .and. ! Mar 2021
     &               ERRTEST .LE. CUTWIN_ERRTEST(2)

          LSIG = Xnsig .GE. cutwin_snrmin_filt(1,ifilt)
     &     .and. Tobs  .GE. cutwin_Tobs(1)
     &     .and. Tobs  .LE. cutwin_Tobs(2)
     &     .and. Trest .GE. cutwin_Trest(1)
     &     .and. Trest .LE. cutwin_Trest(2)
     &     .and. MJD8  .GE. cutwin_MJD(1)
     &     .and. MJD8  .LE. cutwin_MJD(2)
     &     .and. .not. LXMJD     ! Feb 2012
     &     .and. LLAM            ! rest-frame lambda OK (7/08/08)
     &     .and. LPSF .and. LZPERR .and. LPP    ! Feb 2020
     &     .and. LERRTEST                       ! Mar 2021
     &     .and. fluxcal_err >  0.0    ! flux err is > 0

          IF ( .NOT. LSIG ) GOTO 201 ! Nov 30, 2011

c set use-flag for this epoch
          ISNLC_SNRECON_USE(ep) = 1

          if ( USE4SNRMAX ) then
             SNLC_SNRMAX_FILT(0)     =
     &            MAX ( SNLC_SNRMAX_FILT(0), Xnsig )
             SNLC_SNRMAX_FILT(ifilt) =
     &            MAX ( SNLC_SNRMAX_FILT(ifilt), Xnsig )
          endif

          if ( Fluxcal > SNLC_FLUXCALMAX(ifilt) ) then
             SNLC_FLUXCALMAX(ifilt)     = Fluxcal
             SNLC_FLUXCALMAX_ERR(ifilt) = Fluxcal_err
          endif

          EXIST_FILT(ifilt) = .TRUE.
          ISNLC_NEPOCH_USE  = ISNLC_NEPOCH_USE + 1

c track number of filters that pass SNRMAX cut
          LTEST = XNSIG .GE. CUTWIN_SNRMAX(1)
          LTMP  = USE4SNRMAX .and. (.not. LSNRMAX(ifilt))

          IF ( LTEST .and. LTMP ) THEN
             NBAND_SNRMAX = NBAND_SNRMAX + 1
             LSNRMAX(ifilt) = .TRUE.
          ENDIF

c repeat for 2nd SNRMAX2 cut
          LTEST = XNSIG .GE. CUTWIN_SNRMAX2(1)
          LTMP  = USE4SNRMAX .and. (.not. LSNRMAX2(ifilt))
          IF ( LTEST .and. LTMP ) THEN
             NBAND_SNRMAX2 = NBAND_SNRMAX2 + 1
             LSNRMAX2(ifilt) = .TRUE.
          ENDIF

c check PHOTPROB (Mar 2018)
          PHOTPROB = SNLC_PHOTPROB(ep)
          if ( PHOTPROB > -0.0001 ) then
             SNLC_PHOTPROB_MIN = MIN(SNLC_PHOTPROB_MIN,PHOTPROB)
             ISNLC_NEPOCH_PHOTPROB = ISNLC_NEPOCH_PHOTPROB + 1
          endif

c if PHOTFLAG detection bit is set by user, compute MJD of first & last detection
          PHOTFLAG = ISNLC_PHOTFLAG(ep)
          if ( IAND(PHOTFLAG,PHOTFLAG_DETECT) > 0 ) then
             ISNLC_NEPOCH_DETECT = ISNLC_NEPOCH_DETECT + 1
             if ( ISNLC_NEPOCH_DETECT == 1 ) then
                SNLC8_MJD_DETECT_FIRST = MJD8
             endif
             SNLC8_MJD_DETECT_LAST = MJD8
          endif

c check for trigger bit set by survey (5.2019)
          if ( IAND(PHOTFLAG,PHOTFLAG_TRIGGER) > 0 ) then
             SNLC8_MJD_TRIGGER = MJD8
          endif

          CALL CCD_AREAFRAC(ep)
          IF ( SNLC_AREAFRAC(ep) > -0.001 ) then
             SUM_AREAFRAC = SUM_AREAFRAC + SNLC_AREAFRAC(ep)
          ENDIF

201     CONTINUE     ! come here of LSIG fails

200   CONTINUE  ! NEWMJD

c - - - - - -  -

      SNLC_TLIVE_DETECT =
     &   SNGL(SNLC8_MJD_DETECT_LAST - SNLC8_MJD_DETECT_FIRST)

      ISNLC_NFILT_SNRMAX    = NBAND_SNRMAX
      ISNLC_NFILT_SNRMAX2   = NBAND_SNRMAX2

      ORDER = -1
      CALL SORTFLOAT( NFILTDEF_SURVEY, SNLC_SNRMAX_FILT(1),
     &                 ORDER, INDEX_SORT(1) )

      DO isort  = 1, NFILTDEF_SURVEY
         ifilt  = INDEX_SORT(isort)
         SNRMAX = SNLC_SNRMAX_FILT(ifilt)
         SNLC_SNRMAX_SORT(isort) = SNRMAX
      ENDDO

c -----------------------------------------
      CALL GET_USERTAG(SNLC_CCID )

c ----------------------------------------
c Oct 2014: check for multi-season activity

      CALL MULTISEASON(IFLAG_ANA)

c check epochs above/below threshold
      ISNLC_CUTFLAG_REQEP = ISTAT_REQUIRE_EPOCHS()

c evalute cuts on PRIVATE & SIMVAR variables
      CALL EVAL_PRIVATEVAR_CUTS()
      CALL EVAL_SIMVAR_CUTS()

c check option to estimate LC width
      CALL GET_SIM_LCWIDTH(1)

c check option to compute PROB_TRUEFLUX_CALC per band
      CALL PROB_TRUEFLUX_CALC(-1)

c May 2017: load ADDCOL arrays
      CALL TABLE_ADDCOL_LOAD()

      IF ( ISNLC_NEPOCH_USE > 0 ) then
        SNLC_AREAFRAC_AVG = SUM_AREAFRAC/float(ISNLC_NEPOCH_USE)
      ENDIF

      RETURN
      END   ! end of SNRECON

C =============================
CDECK  ID>,  SET_REDSHIFTS. 
      SUBROUTINE SET_REDSHIFTS()
c
c Created Jun 2021
c Called near beginning of SNRECON, this is a driver routine
c to finalize redshifts:
c  + option to use host photo-z
c  + fix for missing zHELIO (on very old surveys)
c  + systematic shifts
c  + etc ...

      IMPLICIT NONE

c +CDE,SNDATCOM.
c +CDE,SNLCINP.

C -------------- BEGIN ----------

c Check option to use host photo-z as redshift.
      CALL SET_SNHOST_ZPHOT()

c if ZHELIO < 0, convert zCMB -> zHELIO
      CALL SET_ZHELIO()

c check for systematic shifts
      CALL SET_zSHIFT()

      RETURN
      END  ! end SET_REDSHIFTS

C =============================
CDECK  ID>,  SET_ZHELIO. 
      SUBROUTINE SET_ZHELIO()

C Creatd Feb 25 2018
c If SNLC_ZHELIO < 0, transform from zCMB.
c Otherwise, check zHEL <-> zCMB transformation.
c If zCMB < 0 for TEXT format, compute zCMB from zHEL.
c
c  Jun 8 2020
c   + fix awful bug with sign of OPT sent to translator.
c      was translating zHELIO -> CMB instead of zCMB -> zHELIO
c   + if SNLC_HELIO[CMB] are both given in data file, make
c     crosscheck here using zTOL_HELIO2CMB test on dz/z
c
c Mar 15 2021: if zCMB < 0 for text format, use computed value.
c Jun 07 2022: do not abort on bad tolerance if REFORMAT_SNANA=T
c Jan 28 2024: do NOT check zTOL if zERR > 1.0 due to sim artifact
c              from GENSIGMA_REDSHIFT option;
c                https://github.com/RickKessler/SNANA/issues/1265
c
c ---------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER OPT
      CHARACTER EQ*4, FNAM*12
      REAL*8  ZHEL8, ZCMB8, DZ8, zRATIO8
      LOGICAL BADz, SKIP_BADz

      REAL*8 zhelio_zcmb_translator ! function

C ------------- BEGIN ------------

      FNAM = 'SET_ZHELIO'

c now we have undefined zCMB

      EQ     = 'eq' // char(0)

c don't apply test on VERY low redshifts to avoid silly round-off
c or truncation errors. This is a hack to protect DES DIFFIMG that
c has redshifts written as %.4f. Next dataFile update will have %.6f
c precisions and then can apply test all the way down to z ~ 1E-4

      IF ( SNLC_ZHELIO > 0.003 ) THEN  ! 0.003 is temp hack; should be 1E-4
         OPT    = +1  ! --> convert ZHEL to ZCMB
         ZHEL8 = DBLE(SNLC_ZHELIO)
         ZCMB8 =
     &      zhelio_zcmb_translator(ZHEL8,SNLC8_RA,SNLC8_DEC,EQ,OPT, 4)

c For TEXT format only, set zCMB if not provided (Mar 15 2021);
c allows quick/sloppy makeDataFiles with real data.
         IF ( SNLC_zCMB < 0.0 .and. FORMAT_TEXT ) THEN
           SNLC_zCMB     = SNGL(ZCMB8)
           SNLC_zCMB_ERR = SNLC_ZHELIO_ERR
         ENDIF

         zRATIO8 = zCMB8/DBLE(SNLC_zCMB)
         DZ8     = abs(1.0 - zRATIO8)

         BADz      = ( SNLC_zCMB > 0.0 .and. DZ8 > zTOL_HELIO2CMB )
         SKIP_BADz = REFORMAT_SNANA .or. (SNLC_ZHELIO_ERR .GE. 0.9999)

         if ( BADz .and. .NOT.SKIP_BADz ) THEN
            CALL PRINT_PREABORT_BANNER(FNAM(1:10)//char(0),12)
            print*,' zHEL(dataFile) = ', SNLC_ZHELIO
            print*,' zCMB(dataFile) = ', SNLC_ZCMB
            print*,' zCMB(compute)  = ', ZCMB8
            print*,' zRATIO = zCMB(compute)/zCMB(dataFile) = ',
     &                 sngl(zRATIO8)
            print*,' zTOL_HELIO2CMB = ', zTOL_HELIO2CMB
            C1ERR='Computed zCMB (from zHEL) outside tolerance w.r.t.'
            C2ERR='REDSHIFT_CMB in data file for CID=' // SNLC_CCID
            CALL MADABORT(FNAM,C1ERR,C2ERR)
         endif

      ELSE if ( SNLC_ZHELIO < 0.0 ) THEN
         OPT    = -1 ! --> convert CMB -> zHEL
cc         OPT    = +1 ! --> BUG
         ZCMB8  = DBLE ( SNLC_ZCMB )
         ZHEL8  =
     &    zhelio_zcmb_translator(ZCMB8,SNLC8_RA,SNLC8_DEC,EQ,OPT, 4)

         SNLC_ZHELIO       = SNGL(ZHEL8)
         SNLC_ZHELIO_ERR   = SNLC_ZCMB_ERR
         SNLC_REDSHIFT     = SNLC_ZHELIO
         SNLC_REDSHIFT_ERR = SNLC_ZHELIO_ERR
      ENDIF

      RETURN
      END   ! end SET_ZHELIO

C =============================================
CDECK  ID>,  SET_SNHOST_ZPHOT. 
      SUBROUTINE SET_SNHOST_ZPHOT

c if USE_SNHOST_ZPHOT=T then set redshift variables to host zphot.
c This ignores accurate specz to enable using photo-z.

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER OPT
      CHARACTER EQ*4
      REAL*8  ZCMB8, ZHEL8

      REAL*8 zhelio_zcmb_translator ! function
C -------------- BEGIN ----------------

      IF ( .not. (USE_SNHOST_ZPHOT .or. USE_HOSTGAL_PHOTOZ) ) RETURN

      if ( .not. EXIST_SNHOST_ZPHOT ) then
          C1ERR = 'Cannot USE_HOSTGAL_PHOTOZ for CID='//SNLC_CCID
          C2ERR = 'Check data files, or set USE_HOSTGAL_PHOTOZ=F'
          CALL MADABORT("SNRECON", c1err, c2err )
      endif

      OPT    = 1     ! --> convert ZHEL to ZCMB
      EQ     = 'eq' // char(0)
      ZHEL8  = DBLE( SNHOST_ZPHOT(1) )
      ZCMB8  =
     &    zhelio_zcmb_translator(ZHEL8,SNLC8_RA,SNLC8_DEC,EQ,OPT,4)

      SNLC_ZCMB         = SNGL(ZCMB8)
      SNLC_ZHELIO       = SNGL(ZHEL8)
      SNLC_REDSHIFT     = SNGL(ZHEL8)

      SNLC_ZHELIO_ERR     = SNHOST_ZPHOT_ERR(1)
      SNLC_ZCMB_ERR       = SNHOST_ZPHOT_ERR(1)
      SNLC_REDSHIFT_ERR   = SNHOST_ZPHOT_ERR(1)

      RETURN
      END     ! end SET_SNHOST_ZPHOT

C =============================================
CDECK  ID>,  SET_zSHIFT. 
      SUBROUTINE SET_zSHIFT

c Created Jun 5 2021
c Apply systematic z-shifts passed from &SNLCINP

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      LOGICAL LSHIFT_FINAL, LSHIFT_HOST_PHOTOZ, LSHIFT_HOST_SPECZ
      INTEGER OPT
      REAL    zshift

      REAL*8 zhelio_zcmb_translator ! function
C -------------- BEGIN ----------------

c bail if none of the zSHIFT options are used
      if ( .not. DOzSHIFT ) RETURN

      LSHIFT_FINAL       = ( REDSHIFT_FINAL_SHIFT .NE. 0.0 )
      LSHIFT_HOST_SPECZ  = ( HOSTGAL_SPECZ_SHIFT  .NE. 0.0 )
      LSHIFT_HOST_PHOTOZ = ( HOSTGAL_PHOTOZ_SHIFT .NE. 0.0 )

      zshift = -9.0
      IF ( LSHIFT_FINAL ) THEN
         zshift  = REDSHIFT_FINAL_SHIFT
      ENDIF

      IF ( LSHIFT_HOST_SPECZ ) THEN
         if ( SNHOST_ZSPEC(1) == SNLC_REDSHIFT ) then
            zshift = HOSTGAL_SPECZ_SHIFT + REDSHIFT_FINAL_SHIFT
            SNHOST_ZSPEC = SNHOST_ZSPEC + zshift
         endif
      ENDIF

      IF ( LSHIFT_HOST_PHOTOZ ) THEN
         if ( SNHOST_ZPHOT(1) == SNLC_REDSHIFT ) then
            zshift = HOSTGAL_PHOTOZ_SHIFT + REDSHIFT_FINAL_SHIFT
            SNHOST_ZPHOT = SNHOST_zPHOT + zshift
         endif
      ENDIF

      IF ( zshift > 0.0 ) THEN
         if ( SNLC_REDSHIFT > 0.) SNLC_REDSHIFT = SNLC_REDSHIFT+ zshift
         if ( SNLC_ZHELIO   > 0.) SNLC_ZHELIO   = SNLC_ZHELIO  + zshift
         if ( SNLC_ZCMB     > 0.) SNLC_ZCMB     = SNLC_ZCMB    + zshift
      ENDIF

      RETURN
      END     ! end SET_zSHIFT

C ============================================
CDECK  ID>,  IS_ZSPEC. 
      LOGICAL FUNCTION IS_ZSPEC()

c Created March 20 2024 by R.Kessler and A.Mitra
c Return True if best redshift is a spec-z.
c Optimal logic is to use MASK_REDSHIFT_SOURCE that
c explcitly sets bit0 for host zspec and bit1 for SN zspec.
c However, if this MASK is not provided, one can assume
c specz if redshift error is less than &SNLCINP variable
c QUANTILE_ZERRMIN.

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c define local zspec mask;
c   grep MASK_REDSHIFT_SOURCE sndata.h
      INTEGER MASK_ZSPEC_SOURCE
      PARAMETER ( MASK_ZSPEC_SOURCE = 3) ! 1=zspec_host, 2=zspec(SN)

      IS_ZSPEC = (SNLC_REDSHIFT_ERR < QUANTILE_ZERRMIN) .or.
     &           (IAND(ISNLC_zSOURCE,MASK_ZSPEC_SOURCE) > 0)

      RETURN
      END

C ===============================
CDECK  ID>,  SET_SNHOST_CONFUSION. 
      SUBROUTINE SET_SNHOST_CONFUSION()
c
c Created Sep 2 2022
c Compute HOST_CONFUSION based on Eq 3 in Gupta et al, 2016
c

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



      REAL*8   HC, DDLR_LIST(MXSNHOST)
      INTEGER  igal, NMATCH2
      LOGICAL LDMP / .FALSE. /
      character cCID*40

      REAL*8   HOST_CONFUSION
      EXTERNAL HOST_CONFUSION   ! see sntools.c

C ----------- BEGIN -------------

      SNHOST_CONFUSION = -9.0

      NMATCH2 = SNHOST_NMATCH2

c only the first MXSNHOST matches are stored
      if ( NMATCH2 > MXSNHOST ) NMATCH2 = MXSNHOST

      if ( NMATCH2 .LE. 1 ) RETURN

c convert single precions to double precision
      DO igal = 1, NMATCH2
        DDLR_LIST(igal) = DBLE(SNHOST_DDLR(igal))
      ENDDO
      cCID = SNLC_CCID(1:ISNLC_LENCCID) // char(0)
      HC = HOST_CONFUSION(cCID,NMATCH2,DDLR_LIST,40)

      IF ( LDMP ) THEN
         print*,' xxx ----------------------------------------- '
         print*, ' xxx DUMP for SET_SNHOST_CONFUSION '
         write(6,60) SNLC_CCID(1:12), NMATCH2,
     &         DDLR_LIST(1), DDLR_LIST(2)
60       format('  xxx CID=',A, 3x, 'NMATCH=',I2, 3x,'DDLR=', 2F9.3 )
         print*,' xxx HOST_CONFUSION = ', HC
         print*,' xxx '
 	 CALL FLUSH(6)
      ENDIF

      SNHOST_CONFUSION = SNGL(HC)

      RETURN
      END   ! end SET_SNHOST_CONFUSION

C ===============================
CDECK  ID>,  SET_MAG. 
      SUBROUTINE SET_MAG(ep)

C Created Jan 23 2018
C Compute observer mag SNLC_MAG(ep) to reduce
C data volume in files. Note that SNLC_MAGERR
c is not set because it is not used.
C
C Aug 2022: check LDMP_SATURATE
c
      IMPLICIT NONE

      INTEGER ep  ! (I) epoch index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      REAL FLUXCAL, FLUXCAL_ERR, MAG, ZP
      INTEGER IFILT_OBS
      CHARACTER CFILT*2
C --------- BEGIN ------------

      Fluxcal      = SNLC_FLUXCAL(ep)
      Fluxcal_err  = SNLC_FLUXCAL_ERRTOT(ep)

      IF ( FLUXCAL_ERR > 0.99E8 ) THEN
        MAG = MAG_SATURATE
        if ( LDMP_SATURATE ) then
             IFILT_OBS = ISNLC_IFILT_OBS(ep)
             cfilt     = FILTDEF_STRING(ifilt_obs:ifilt_obs)
             write(6,20) SNLC_CCID(1:8), SNLC_ZHELIO,
     &                   SNLC8_MJD(ep), CFILT(1:1), SIM_EPMAGOBS(ep)
20           format(T2,'SATURATION: ',
     &          'CID=',A8, 2x, 'zHEL=',F6.4, 2x,
     &          'MJD=',F9.3,'-',A, 2x, 'TrueMag=',F8.3 )
        endif
      ELSE IF ( FLUXCAL < 1.0E-9 ) THEN
        MAG = 128.0  ! negative flux
      ELSE
        ZP  = SNGL(ZEROPOINT_FLUXCAL_DEFAULT)
        MAG = ZP - 2.5*LOG10(FLUXCAL)
      ENDIF

      SNLC_MAG(ep) = MAG

      RETURN
      END    ! end SET_MAG


C ===============================
CDECK  ID>,  SET_SBMAG. 
      SUBROUTINE SET_SBMAG(ifilt)

C Created Feb 17 2018
C Compute surface-brightness mag SNLC_SBMAG(ep) from SB flux.
C
c Mar 23 2021: SBFLUXMIN -> 1.0 (was 0.1)
c Aug 11 2021: SBFLUX = -99 -> SBMAG=99
c
      IMPLICIT NONE
      INTEGER ifilt  ! (I) sparse filter index

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


      REAL SBFLUX, SBMAG, SBFLUXMIN, ZP
C --------- BEGIN ------------
      SBFLUX = SNHOST_SBFLUXCAL(ifilt)
      SBFLUXMIN = 1.0

      ZP = SNGL( ZEROPOINT_FLUXCAL_DEFAULT )
      IF ( SBFLUX > SBFLUXMIN ) THEN
         SBMAG = ZP - 2.5*LOG10(SBFLUX)
      ELSE
         SBMAG = ZP - 2.5*LOG10(SBFLUXMIN)
      ENDIF

      IF ( SBFLUX .LE. -999.0 ) SBMAG = 99.0 ! Aug 2021 - undefined SB

      SNHOST_SBMAG(ifilt) = SBMAG
      RETURN
      END

C ========================
CDECK  ID>,  PARSE_SIMVAR_CUTS. 
      SUBROUTINE PARSE_SIMVAR_CUTS()
      IMPLICIT NONE

c Dec 2018
c Parse &SNLCINP input SIMVAR_CUTWIN_STRING


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER NTMP, i, NWD, LWD
      CHARACTER ctmp1*60, ctmp2*60, ctmp3*60, FNAM*20

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C --------- BEGIN ---------
      IF ( .NOT. ISJOB_SIM )  RETURN
      IF ( SIMVAR_CUTWIN_STRING .EQ. '' ) RETURN

      FNAM = 'PARSE_SIMVAR_CUTS'
      NTMP = 0
      LWD = MXCHAR_CUTNAME-2
      NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_STRING,
     &     SIMVAR_CUTWIN_STRING(1:LWD)//char(0), FNAM//char(0), LWD, 20)

      DO i = 1, NWD, 3
         NTMP = NTMP + 1
         CALL get_PARSE_WORD_fortran(i+0, ctmp1, LWD)
         CALL get_PARSE_WORD_fortran(i+1, ctmp2, LWD)
         CALL get_PARSE_WORD_fortran(i+2, ctmp3, LWD)
         SIMVAR_CUTWIN_LIST(NTMP) = CTMP1(1:40)
         READ(CTMP2,*)  SIMVAR_CUTWIN(1,NTMP)
         READ(CTMP3,*)  SIMVAR_CUTWIN(2,NTMP)
      ENDDO
      NSIMVAR_CUTWIN = NTMP

      if ( NTMP > MXCUT_PRIVATE ) then
         write(c1err,61) NTMP, MXCUT_PRIVATE
 61      format('NSIMVAR_CUTWIN=',I2,' exceeds bound of ', I2)
         c2err = 'Check &SNLCINP input SIMCAR_CUTWIN_STRING'
         CALL MADABORT(FNAM, c1err, c2err )
      endif

      DO i = 1, NTMP
         LWD = INDEX(SIMVAR_CUTWIN_LIST(i),' ') - 1
         write(6,77) SIMVAR_CUTWIN_LIST(i)(1:LWD),
     &        SIMVAR_CUTWIN(1,i), SIMVAR_CUTWIN(2,i)
 77      format(T5,'SIMVAR_CUT on ', A20,' : ', F10.4,' to ', F10.4);
      ENDDO

      RETURN
      END   ! end PARSE_SIMVAR_CUTS


C ================================
CDECK  ID>,  EVAL_SIMVAR_CUTS. 
      SUBROUTINE EVAL_SIMVAR_CUTS()

c Created Dec 2018
c Evaluate PASS_SIMCUTS based on user-input SIMVAR_CUTWIN_STRING
c Check hard-coded SIM_xxx names, and also check SIMSED_xxx names.
c
c Nov 25 2019: check NEP_SIM_MAGOBS = number os SIM_MAGOBS < 99
c Jun 23 2020: abort of VARNAME not found

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      LOGICAL FOUND
      INTEGER i, ipar, LENTMP
      REAL*8  VMIN, VMAX
      CHARACTER VARNAME*40, CTMP*60, VARNAME_TMP*60, FNAM*20

C --------------- BEGIN ------------

      IF ( NSIMVAR_CUTWIN == 0 ) RETURN
      FNAM = 'EVAL_SIMVAR_CUTS'

      DO 100 i = 1, NSIMVAR_CUTWIN
         FOUND   = .FALSE.
         VMIN    = DBLE( SIMVAR_CUTWIN(1,i) )
         VMAX    = DBLE( SIMVAR_CUTWIN(2,i) )
         VARNAME = SIMVAR_CUTWIN_LIST(i)
         if ( VARNAME .EQ. 'SIM_ZCMB' ) then
            FOUND   = .TRUE.
            if ( SIM_REDSHIFT_CMB < VMIN ) PASS_SIMCUTS = .FALSE.
            if ( SIM_REDSHIFT_CMB > VMAX ) PASS_SIMCUTS = .FALSE.

         else if ( VARNAME .EQ. 'SIM_PEAKMJD' ) then
            FOUND   = .TRUE.
            if ( SIM_PEAKMJD < VMIN ) PASS_SIMCUTS = .FALSE.
            if ( SIM_PEAKMJD > VMAX ) PASS_SIMCUTS = .FALSE.

         else if ( VARNAME .EQ. 'SIM_SALT2c' ) then
            FOUND   = .TRUE.
            if ( SIM_COLORPAR < VMIN ) PASS_SIMCUTS = .FALSE.
            if ( SIM_COLORPAR > VMAX ) PASS_SIMCUTS = .FALSE.

         else if ( VARNAME .EQ. 'SIM_SALT2x1' ) then
            FOUND   = .TRUE.
            if ( SIM_SHAPEPAR < VMIN ) PASS_SIMCUTS = .FALSE.
            if ( SIM_SHAPEPAR > VMAX ) PASS_SIMCUTS = .FALSE.

         else if ( VARNAME .EQ. 'NEP_SIM_MAGOBS' ) then
            FOUND   = .TRUE.
            if ( NEP_SIM_MAGOBS < int(VMIN) ) PASS_SIMCUTS = .FALSE.
            if ( NEP_SIM_MAGOBS > int(VMAX) ) PASS_SIMCUTS = .FALSE.
         endif

c check SIMSED variables
         DO IPAR    = 1, NPAR_SIMSED
            CTMP    = SIMSED_PARNAME(ipar)
            LENTMP  = INDEX(CTMP,' ') - 1
            VARNAME_TMP = 'SIMSED_' // CTMP(1:LENTMP)
            if ( VARNAME .EQ. VARNAME_TMP ) then
            FOUND   = .TRUE.
               if ( SIMSED_PARVAL(ipar) < VMIN ) PASS_SIMCUTS = .FALSE.
               if ( SIMSED_PARVAL(ipar) > VMAX ) PASS_SIMCUTS = .FALSE.
            endif
         ENDDO

         if ( .NOT. FOUND ) then
            c1err = 'Could not evaluate cut on ' // VARNAME(1:20)
            c2err = 'Check &SNLCINP  SIMVAR_CUTWIN_STRING'
            CALL MADABORT(FNAM, c1err, c2err )
         endif
 100  CONTINUE


      RETURN
      END  ! ene EVAL_SIMVAR_CUTS

C ======================================
CDECK  ID>,  PRIVATECUTS. 
      SUBROUTINE EVAL_PRIVATEVAR_CUTS()

c
c Created Nov 3 2014
c Evaluate optional cuts on private variables.
c PASS_PRIVCUTS has been initialized to TRUE; set this
c flag to FALSE if any private variable cut-window fails.
c The private cuts are defined by &SNLCINP variable

c PRIVATE_CUTWIN_STRING = 'VARNAME  CUTMIN  CUTMAX'
c   or
c PRIVATE_CUTWIN_STRING = 'VARNAME  != VETO_VALUE'
c
c Apr 27 2021: refactor to allow veto option
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



      INTEGER ivar, APPLY_CUTFLAG
      REAL*8 VAL, CUTMIN, CUTMAX
C -------------- BEGIN ------------

      IF ( NCUT_PRIVATE .EQ. 0 ) RETURN

      DO 100 ivar = 1, NVAR_PRIVATE
         APPLY_CUTFLAG = USE_PRIVATE_CUTWIN(ivar)
         if ( APPLY_CUTFLAG == 0 ) goto 100

         ! strip off info stored from init stage
         VAL    = PRIVATE_VALUE(ivar)
         CUTMIN = PRIVATE_CUTWIN(1,IVAR)
         CUTMAX = PRIVATE_CUTWIN(2,IVAR)

         IF ( APPLY_CUTFLAG < 0 ) then
            ! veto cut (Apr 2021)
            if ( VAL == CUTMIN ) PASS_PRIVCUTS = .FALSE.
         ELSE
            ! regular CUT-window
            if(VAL<CUTMIN .or. VAL>CUTMAX ) PASS_PRIVCUTS = .FALSE.
         ENDIF

         if ( .not. PASS_PRIVCUTS ) RETURN

 100  CONTINUE

      RETURN
      END    ! end of EVAL_PRIVATEVAR_CUTS()

C ===============================================
CDECK  ID>,  INIFUDGEFLUX. 
      SUBROUTINE INIT_FUDGE_FLUXCAL(IERR)

c
c Init fudges on FLUXCAL[ERR]
c Apr 2017: call INIT_NONLIN().
c Dec 2017: use IGNOREFILE function on FUDGE_HOSTNOISE_FILE
c              to allow NONE
c Feb 15 2018: call INIT_FLUXERRMODEL
c Apr 15 2018: mass OPTMASK argument to INIT_FLUXERRMODEL

      IMPLICIT NONE

      INTEGER IERR  ! (I) return 0 if all ok


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LL, OPTMASK, MSKTMP, RDMASK
      CHARACTER cFILE*(MXCHAR_FILENAME), cNONE*6, FNAM*20
      LOGICAL FORCE_FLUXERRCOR, FORCE_FLUXCOR, VALID_FILE
      LOGICAL ALLOW_FLUXERRCOR, ALLOW_FLUXCOR, ISDATA

c function in sntools.c
      INTEGER IGNOREFILE
C --------------- BEGIN ----------------

      IERR = 0
      FNAM = 'INIT_FUDGE_FLUXCAL'

      DOFUDGE_HOSTNOISE    = .FALSE.
      DOFUDGE_NONLIN       = .FALSE.
      DOFUDGE_FLUXERRMODEL = .FALSE.
      FORCEMASK_FLUXCOR    = 0
      ISDATA = (.NOT. LSIM_SNANA)

c --------------------------------------------------------
c check FORCE option in case flux fudges already applied

      RDMASK = ISNLC_RDMASK_FLUXCOR_SNANA

      MSKTMP = MASK_FLUXERRCOR_SNANA
      CALL SETFORCE_FLUXCOR_SNANA(MSKTMP,FLUXERRMODEL_FILE)
      CALL SETFORCE_FLUXCOR_SNANA(MSKTMP,FUDGE_HOSTNOISE_FILE)
      FORCE_FLUXERRCOR = ( IAND(MSKTMP,FORCEMASK_FLUXCOR) > 0 )
      ALLOW_FLUXERRCOR =
     &  FORCE_FLUXERRCOR .or. (IAND(RDMASK,MSKTMP)==0 )

      MSKTMP = MASK_FLUXCOR_SNANA
      CALL SETFORCE_FLUXCOR_SNANA(MSKTMP,MAGCOR_FILE)
      CALL SETFORCE_FLUXCOR_SNANA(MSKTMP,NONLINEARITY_FILE)
      FORCE_FLUXCOR  = ( IAND(MSKTMP,FORCEMASK_FLUXCOR) > 0 )
      ALLOW_FLUXCOR =
     &  FORCE_FLUXCOR .or. (IAND(RDMASK,MSKTMP)==0 )

c ------------------------------------------------
      CALL ENVreplace(FUDGE_HOSTNOISE_FILE)
      LL    = INDEX(FUDGE_HOSTNOISE_FILE,' ')-1
      cFILE = FUDGE_HOSTNOISE_FILE(1:LL) // char(0)
      IF ( IGNOREFILE(cFILE,LL) == 0 ) THEN
         DOFUDGE_HOSTNOISE = .TRUE.
         CALL INIT_NOISEMODEL_HOST_LEGACY( cFILE, LL );
      ENDIF

c Apr 2017: check nonlinearity from user-supplied map
      CALL ENVreplace(NONLINEARITY_FILE);
      LL    = INDEX(NONLINEARITY_FILE,' ')-1
      cFILE = NONLINEARITY_FILE(1:LL) // char(0)
      if ( IGNOREFILE(cFILE,LL) == 0 ) then
         DOFUDGE_NONLIN       = .TRUE.
         CALL INIT_NONLIN(cFile,LL)
      endif

c ------------------------------
c Feb 2018: check FLUXERRMAPs for DATA

      OPTMASK = FLUXERRMODEL_OPTMASK
      if ( REQUIRE_DOCANA .NE. 0 ) then
c   note that MASK_REQUIRE_DOCANA_FLUXERRMAP=1024
c   in sntools_fluxErrModels.h
         FLUXERRMODEL_OPTMASK = FLUXERRMODEL_OPTMASK + 1024
      endif

      CALL ENVreplace(FLUXERRMODEL_FILE);
      LL    = INDEX(FLUXERRMODEL_FILE,' ')-1
      cFILE = FLUXERRMODEL_FILE(1:LL) // char(0)
      VALID_FILE = (IGNOREFILE(cFILE,LL) == 0)
      if ( VALID_FILE ) then
        CALL PRINTMSG_FLUXCOR(MASK_FLUXERRCOR_SNANA,"FLUXERRMODEL_FILE")
      endif
      IF ( VALID_FILE .and. ALLOW_FLUXERRCOR .and. ISDATA ) THEN
         cNONE = 'NONE' // char(0)
         DOFUDGE_FLUXERRMODEL = .TRUE.
         CALL INIT_FLUXERRMODEL(OPTMASK,cFile,cNONE,cNONE,LL,4,4)
      ENDIF

c March 2018: check FLUXERRMAPs for SIM
      CALL ENVreplace(SIM_FLUXERRMODEL_FILE);
      LL    = INDEX(SIM_FLUXERRMODEL_FILE,' ')-1
      cFILE = SIM_FLUXERRMODEL_FILE(1:LL) // char(0)
      IF ( IGNOREFILE(cFILE,LL) == 0  .and. LSIM_SNANA ) THEN
         cNONE = 'NONE' // char(0)
         DOFUDGE_FLUXERRMODEL = .TRUE.
         CALL INIT_FLUXERRMODEL(OPTMASK,cFile,cNONE,cNONE,LL,4,4)
      ENDIF

c ------------------------------------------------
c check MAGCOR (e.g. chromatic corrections) for data
c CALL INIT_MAGCOR()

      CALL ENVreplace(MAGCOR_FILE);
      LL    = INDEX(MAGCOR_FILE,' ')-1
      cFILE = MAGCOR_FILE(1:LL) // char(0)
      VALID_FILE = (IGNOREFILE(cFILE,LL) == 0)
      if ( VALID_FILE ) then
        CALL PRINTMSG_FLUXCOR(MASK_FLUXCOR_SNANA,"MAGCOR_FILE")
      endif

      IF ( VALID_FILE .and. ALLOW_FLUXCOR .and. ISDATA ) THEN
         CALL INIT_MAGCOR(MAGCOR_FILE);
      ENDIF

c check SIM_MAGCOR_FILE
      CALL ENVreplace(SIM_MAGCOR_FILE);
      LL    = INDEX(SIM_MAGCOR_FILE,' ')-1
      cFILE = SIM_MAGCOR_FILE(1:LL) // char(0)
      IF ( IGNOREFILE(cFILE,LL) == 0  .and. LSIM_SNANA ) THEN
         CALL INIT_MAGCOR(SIM_MAGCOR_FILE);
      ENDIF

c - - - - - - - - - - - - -
c error checking
      if ( DOFUDGE_HOSTNOISE .and. DOFUDGE_FLUXERRMODEL ) then
         c1err = 'Cannot specify FUDGE_HOSTNOISE_FILE ' //
     &           'and FLUXERRMODEL_FILE'
         c2err = 'Use one file or the other.'
         CALL MADABORT(FNAM, c1err, c2err )
      endif

      RETURN
      END       ! end of INIT_FUDGE_FLUXCAL


C ==============================
CDECK  ID>,  PRINTMSG_FLUXCOR. 
      SUBROUTINE PRINTMSG_FLUXCOR(INMASK,CORFILE)

c Created Nov 14 2018
c Print appropriate message for FLUXCOR or FLUXERR correction.
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER  INMASK   ! (I) 1=fluxcor, 2=fluxerrcor

      INTEGER  RDMASK, LEN
      LOGICAL  ALLOW, FORCE, ISDATA
      CHARACTER*(*) CORFILE

C ------------------- BEGIN ------------------

      ISDATA = (.NOT. LSIM_SNANA)
      RDMASK = ISNLC_RDMASK_FLUXCOR_SNANA
      LEN    = INDEX(CORFILE,' ') - 1

      FORCE = ( IAND(INMASK,FORCEMASK_FLUXCOR)  > 0   )
      ALLOW = ( FORCE .or. ( IAND(INMASK,RDMASK)==0 ) )

c start with default behavior of ignoring already-applied correction
      IF ( (.NOT. ALLOW) .and. ISDATA ) THEN
         print*,' '
         print*,' !!! '//CORFILE// ' CORRECTION ALREADY APPLIED '
         print*,' !!!  ==> IGNORE '// CORFILE
         print*,' '
      ENDIF

c check option to FORCE correction, even if already applied
      IF ( ALLOW .and. FORCE .and. ISDATA ) THEN
         print*,' '
         print*,' !!! '//CORFILE// ' CORRECTION ALREADY APPLIED '
         print*,' !!! ==> FORCE '//CORFILE//' ANYWAY   '
         print*,' '
      ENDIF

c for sims, give reminder that corrections are not applied to sims.
      IF ( LSIM_SNANA ) THEN
        print*,' '
        print*,'  !!! IGNORE '//CORFILE//' for SIMULATION'
        print*,'  !!!   (or switch to SIM_'//CORFILE//' option)  '
        print*,' '
      ENDIF

      call flush(6)

      RETURN
      END  ! end PRINTMSG_FLUXCOR


C ===============================
CDECK  ID>,  EXEC_FUDGE_FLUXCAL. 
      SUBROUTINE EXEC_FUDGE_FLUXCAL(EP)

c Created Nov 15, 2011 by R.Kessler and J.Marriner
c Fudge FLUXCAL and ERROR based on user namelist option
c FUDGE_FLUXCAL_OFFSET/ERROR
c
c The following arrays are modified
c   - SNLC_FLUXCAL
c   - SNLC_FLUXCAL_ERRTOT
c
c Note that the SNLC_MAG array is not modified !!!
c
c Dec 14, 2011: abort on negative SQERR
c Sep 03, 2013: add FLUXCAL_OFF(ifilt)
c Oct 23, 2013: add use FUDGE_MAG_ERROR
c Aug 27, 2014: add FUDGE_FLUXCAL_ERRPIX (error per pixel x AREA)
c               See ERR2b and DAREA calc.
c
c Mar 06, 2015: check GEN_HOSTNOISE
c Sep 14, 2015: fix dumb bug setting ZP outside if-block
c Apr 17, 2017: call GET_NONLIN(...)
c Feb 16, 2018:
c  + call get_FLUXERRMODEL, float -> double, little refactor
c
c Nov 12, 2018: call EXEC_MAGCOR(ep)
c
c Mar 9 2020:
c   fix awful bug where previous FLUXCAL was used to apply
c   FUDGE_MAG_ERROR. Note RESTORE_DES3YR restores bug.
c
c Dec 2 2022: add string-length args to get_FLUXERRMODEL call.
c
c ------------

      IMPLICIT NONE

      INTEGER EP  ! (I) epoch index and SN index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

c local var

      REAL*8
     &   ERR1, ERR2a, ERR2b, ERR3, ERR_SIM, ERR_DATA
     &  ,ERR_ORIG, SCALE, FUDGE, SNR, SNR_PROTECT, LOGSNR
     &  ,SQERR, SQERR1, SQERR2a, SQERR2b, SQERR3, SQERRHOST, SQERRMAP
     &  ,RDNOISE_pe, FLUXCAL, FLUXCAL_BUG, FLUXADU
     &  ,AREA, NEA, PSFSIG1, PSFSIG2, PSFRATIO
     &  ,GALMAG, SBMAG, SBFLUX, SNSEP, NOISEPAR(2)
     &  ,MJD, GAIN, SKYSIG, ZP, ZPDIF, PARLIST(20)
     &  ,SQTMP, Fscale, Fpe_source, Fpe_sky, GENMAG

      INTEGER*8 GALID
      INTEGER IFILT_OBS, IFILT, OPT, NPAR, LL
      CHARACTER cfilt*2, FNAM*20, cFIELD*32, cBAND*2
      LOGICAL DOFUDGE

c function
      EXTERNAL NoiseEquivAperture, GET_NONLIN, get_FLUXERRMODEL
      REAL*8   NoiseEquivAperture, GET_NONLIN

c ------------ BEGIN ----------------

      FNAM = 'EXEC_FUDGE_FLUXCAL'
      IFILT_OBS = ISNLC_IFILT_OBS(ep)
      IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
      cfilt     = FILTDEF_STRING(ifilt_obs:ifilt_obs)

      SNLC_FLUXCAL(ep) = SNLC_FLUXCAL(ep)
     &     + SNLC_FLUXCAL_OFF(ifilt)               ! offset in data file
     &     + FUDGE_FLUXCAL_OFFSET_FILT(IFILT_OBS)  ! user-nml offset

c get C function arguments
      cBAND        = cfilt(1:1) // char(0)
      LL           = INDEX(SNLC_FIELD(ep), ' ') - 1
      cFIELD       = SNLC_FIELD(ep)(1:LL) // char(0)
      GALID        = SNHOST_OBJID(1)
      SNSEP      = DBLE( SNHOST_ANGSEP(1) )
      GALMAG     = DBLE( SNHOST_MAGOBS(ifilt,1) )
      SBFLUX     = DBLE( SNHOST_SBFLUXCAL(ifilt) )
      SBMAG      = DBLE( SNHOST_SBMAG(ifilt) )
      FLUXCAL    = DBLE( SNLC_FLUXCAL(ep) )
      PSFSIG1    = DBLE( SNLC_PSF_SIG1(EP) )  ! Gauss sigma, pixel
      PSFSIG2    = DBLE( SNLC_PSF_SIG2(EP) )  ! idem, 2nd component
      PSFRATIO   = DBLE( SNLC_PSF_RATIO(EP) )
      NEA        = DBLE( SNLC_PSF_NEA(EP) )
      GAIN       = DBLE( SNLC_GAIN(ep) )
      SKYSIG     = DBLE( SNLC_SKYSIG(ep) )          ! sigma, ADU/pixel
      RDNOISE_pe = DBLE(SNLC_RDNOISE(ep) )  ! e-/pix
      ZP         = DBLE( SNLC_ZEROPT(ep) )
      ZPDIF      = ZP - ZEROPOINT_FLUXCAL_DEFAULT
      MJD        = SNLC8_MJD(EP)
      SNR        = FLUXCAL/ERR1

c - - - - - - - - - - - - - -
      SCALE    = DBLE(FUDGE_FLUXERR_SCALE_FILT(IFILT_OBS))
      ERR_ORIG = DBLE(SNLC_FLUXCAL_ERRTOT(ep))
      ERR1  = ERR_ORIG * SCALE
      ERR2a = DBLE(FUDGE_FLUXCAL_ERROR_FILT(IFILT_OBS))  ! fudge error
      ERR2b = DBLE(FUDGE_FLUXCAL_ERRPIX_FILT(IFILT_OBS)) ! fudge err/pix
      ERR3  = DBLE(FUDGE_MAG_ERROR_FILT(IFILT_OBS))* FLUXCAL ! fudge mag err

      SQERR1     = ERR1  * ERR1
      SQERR2a    = ERR2a * ERR2a
      IF ( ERR2a .LT. 0.0 ) SQERR2a = -SQERR2a
      SQERR2b    = ERR2b * ERR2b   ! * AREA  ! sum in quad over pixels
      SQERR3     = ERR3  * ERR3
      SQERRHOST  = 0.0
      SQERRMAP   = 0.0

c --------------------------------------------
c  Check for map corrections

      IF ( DOFUDGE_HOSTNOISE  ) THEN  ! compute ERRHOST
c call function to return
c  noisePar(1) =  FLUXCAL noise per pixel
c  noisePar(2) =  ERRSCALE to multiply skynoise
         CALL GEN_NOISEMODEL_HOST_LEGACY(cBAND,cFIELD,GALID,
     &           GALMAG, SBMAG, SNSEP, noisePar, 2,30);
         SQTMP     = NOISEPAR(2)**2 - 1.0 ! don't double-count error
         SQERRHOST = SQERR1 * SQTMP
      ENDIF


      IF ( DOFUDGE_FLUXERRMODEL  ) THEN ! compute ERRMAP
        OPT = 0 ; NPAR=0
        SNR_PROTECT = MAX(SNR,0.126)    ! --> LOGSNR >= -0.9
        LOGSNR = log10(SNR_PROTECT)

c  grep IPAR_FLUXERRMAP sntools_fluxErrModels.h
        NPAR = NPAR+1;  PARLIST(NPAR) = MJD
        NPAR = NPAR+1;  PARLIST(NPAR) = PSFSIG1
        NPAR = NPAR+1;  PARLIST(NPAR) = SKYSIG
        NPAR = NPAR+1;  PARLIST(NPAR) = ZP
        NPAR = NPAR+1;  PARLIST(NPAR) = LOGSNR
        NPAR = NPAR+1;  PARLIST(NPAR) = SBMAG
        NPAR = NPAR+1;  PARLIST(NPAR) = GALMAG
        NPAR = NPAR+1;  PARLIST(NPAR) = SNSEP
        CALL  get_FLUXERRMODEL(OPT,ERR1,cBAND,cFIELD,NPAR, PARLIST,
     &            ERR_SIM, ERR_DATA, 2,30 )  ! <== return ERR_SIM, ERR_DATA

        SQERRMAP = (ERR_DATA*ERR_DATA) - SQERR1 ! note: can be negative
      ENDIF


c avoid invalid fluxes.
      IF ( FLUXCAL .EQ. -9.0 ) RETURN

c bail if nothing to do
      DOFUDGE =
     &     ( ERR1  > 0.0 ) .or.
     &     ( ERR2a > 0.0 ) .or.
     &     ( ERR2b > 0.0 ) .or.
     &     ( ERR3  > 0.0 ) .or.
     &     ( SQERRHOST  > 0.0 ) .or.
     &     ( SQERRMAP   > 0.0 )

      if ( .NOT. DOFUDGE ) GOTO 880  ! jump to nonlinearity flux-fudge

      AREA = 0.0
      IF ( ERR2b > 0.0 ) THEN
         ! sum noise over pixels in effective background area
         if ( PSFSIG1 < 0.002 ) then
            c1err = 'Undefined PSF for FUDGE_FLUXCAL_ERRPIX'
            write(c2err,62) SNLC_CCID, MJD, cfilt
 62         format('CID=',A10,' for MJD=', F9.3,'-', A)
            CALL MADABORT(FNAM, c1err, c2err )
         endif
         AREA  = NEA
      ENDIF


      SQERR = SQERR1 + SQERR2a + (SQERR2b*AREA) + SQERR3
     &      + SQERRHOST + SQERRMAP

      IF ( SQERR .LE. 0.0 ) THEN
         CALL PRINT_PREABORT_BANNER(FNAM(1:18)//char(0),40)
         print*,'   ERR1(from data file): ',          sngl(ERR1)
         print*,'   ERR2a(user-fluxcal fudge): ',     sngl(ERR2a)
         print*,'   ERR2b(user-fluxcal fudge/pix): ', sngl(ERR2b)
         print*,'   ERR3(user magerr fudge): ' ,      sngl(ERR3)
         print*,'   ERRHOST(FUDGE_HOSTNOISE_FILE): ',
     &                  sngl( sqrt(SQERRHOST) )
         print*,'   ERRMAP(FLUXERRMODEL_FILE): ',
     &                  sngl( sqrt(SQERRMAP) )
         write(c1err,61)
     &        SNLC_CCID(1:ISNLC_LENCCID), cfilt, MJD
 61      format('Negative flux error for CID=',A, '-',A,
     &         3x, 'and MJD=',F9.3)
         c2err = 'Check error fudges in &SNLCINP'
         CALL MADABORT(FNAM, c1err, c2err )
      ENDIF

      SNLC_FLUXCAL_ERRTOT(ep) = SNGL ( SQRT(SQERR) )

      CALL SETMASK_FLUXCOR_SNANA(MASK_FLUXERRCOR_SNANA)

c ---------------------------
880   CONTINUE
c ---------------------------

c check GET_NONLIN option in sntools_nonlinearity.c
      IF ( DOFUDGE_NONLIN ) THEN

        if ( GAIN < 0.01 .or. SKYSIG < 0.0001 .or. ZP < 0.01 ) then
           CALL PRINT_PREABORT_BANNER(FNAM(1:18)//char(0),40)
           print*,'    BAND    = ', CFILT
           print*,'    GAIN    = ', sngl(GAIN), ' e-/pix'
           print*,'    ZP      = ', sngl(ZP),'  (ADU->MAG)'
           print*,'    SKYSIG  = ', sngl(SKYSIG),' ADU/pix '
           print*,'    RDNOISE = ', sngl(RDNOISE_pe),' e-/pix'
           c1err = 'Canot compute NON-LINEARITY'
           c2err = 'See above values'
           CALL MADABORT(FNAM, c1err, c2err )
        endif

      ! sum noise over pixels in effective background area
        FLUXADU = FLUXCAL * 10.0**(0.4*ZPDIF)

        Fpe_source = FLUXADU * GAIN
        IF ( Fpe_source < 0.0 ) Fpe_source = 0.01 ! must be positive
        Fpe_sky    = NEA * (SKYSIG*GAIN)**2
        GENMAG     = DBLE( SNLC_MAG(ep) )

        Fscale = get_nonlin(cfilt(1:1)//char(0),
     &                      Fpe_source, Fpe_sky, GENMAG, 2 )
        SNLC_FLUXCAL(ep) = SNLC_FLUXCAL(ep) * SNGL(Fscale)
        CALL SETMASK_FLUXCOR_SNANA(MASK_FLUXCOR_SNANA)
      ENDIF

c ---------------------
c mag-corrections; e.g.. chromatic corrections from FGCM
      CALL EXEC_MAGCOR(ep)

      RETURN
      END        ! end EXEC_FUDGE_FLUXCAL

C ===========================================
CDECK  ID>,  SETFORCE_FLUXCOR_SNANA. 
      SUBROUTINE SETFORCE_FLUXCOR_SNANA(MASK,INFILE)

c Created Nov 14 2018
c INFILE = '<fileName>'       --> do nothing
c INFILE = '<fileName FORCE>' --> set MASK bit of FORCEMASK_FLUXCOR
c                                 and set INFILE = fileName
c - - - - - -
      IMPLICIT NONE

      INTEGER MASK         ! (I) mask to set for FORCEMASK
      CHARACTER INFILE*(*) ! (I) name of input file


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER NAME_forC*(MXCHAR_FILENAME), cwd*(MXCHAR_FILENAME), FNAM*30
      INTEGER iwd, NWD, LENFILE,MSKOPT

      LOGICAL  IGNOREFILE_fortran
      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ---------------- BEGIN --------------

      if ( IGNOREFILE_fortran(INFILE) ) RETURN  ! Apr 7 2022

      FNAM      = 'SETFORCE_FLUXCOR_SNANA'
      MSKOPT    = MSKOPT_PARSE_WORDS_STRING
      LENFILE   = INDEX(INFILE,' ') + 10 ! allow FORCE key after space
      NAME_forC = INFILE(1:LENFILE-1)//char(0)
      NWD = STORE_PARSE_WORDS(MSKOPT, NAME_forC,
     &         FNAM//char(0), LENFILE, 30)

      IF ( NWD <= 1 ) RETURN

c with more than 1 word, check for FORCE key

      DO 10 iwd = 1, NWD
         CALL get_PARSE_WORD_fortran(iwd,cwd,LENFILE)

         if ( iwd==1 ) then
            INFILE = cwd
         else if ( cwd(1:5) .EQ. 'FORCE' ) then
            FORCEMASK_FLUXCOR = IOR(FORCEMASK_FLUXCOR,MASK)
         endif
10    CONTINUE


      RETURN
      END ! end of SETFORCE_FLUXCOR_SNANA

C ===========================================
CDECK  ID>,  SETMASK_FLUXCOR_SNANA. 
      SUBROUTINE SETMASK_FLUXCOR_SNANA(MASK)

      IMPLICIT NONE

      INTEGER MASK  ! (I) mask to set

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER ALREADY_SET, FORCE
      CHARACTER FNAM*24

C --------------- BEGIN ------------------

      FNAM = 'SETMASK_FLUXCOR_SNANA'

c first check mask read from data file to see if fluxcor fudge
c was already applied

      ALREADY_SET = IAND(ISNLC_RDMASK_FLUXCOR_SNANA,MASK)
      FORCE       = IAND(FORCEMASK_FLUXCOR,MASK)

      if ( ALREADY_SET > 0 .and. FORCE == 0 ) RETURN

c xxxxxxxxxxxxxxxx
c      if ( ALREADY_SET > 0 .and. FORCE == 0 ) then
c         CMASK(MASK_FLUXCOR_SNANA)    = 'FLUXCOR/MAGCOR'
c         CMASK(MASK_FLUXERRCOR_SNANA) = 'FLUXERRCOR'
c         C1ERR = 'Will not apply ' // CMASK(MASK)
c         C2ERR = 'because data files already include '//CMASK(MASK)
c         CALL MADABORT(FNAM, c1err, c2err )
c      endif
c xxxxxxxxxxxxxxxx

      ISNLC_WRMASK_FLUXCOR_SNANA =
     &     IOR(ISNLC_WRMASK_FLUXCOR_SNANA,MASK)

      RETURN
      END   ! end of SETMASK_FLUXCOR_SNANA

C =================================
CDECK  ID>,  COUNTFIELDS. 
      SUBROUTINE COUNTFIELDS()
c
c Jun 8, 2009 R.Kessler
c
c Fill ISNLC_NFIELD with number of different fields used by this SN.
c NFIELD = 1 for isolated field, but can be > 1 for overlapping fields.
c
c
c --------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &   ep, NEP, i, ovp
     &  ,IDF, IDF_OVPLIST(MXFIELD_OVP)
     &  ,NFIELD, LENTMP, LENTOT, L2

      CHARACTER FIELDTMP*(MXCHAR_FIELDNAME), FNAM*12
      LOGICAL USE, FIRST

C ------------- BEGIN ----------

      NEP    = ISNLC_NEPOCH_STORE
      NFIELD = 0
      FNAM   = 'COUNTFIELDS'

      DO 101 ep = 1, NEP
          IDF   = ISNLC_IDFIELD(ep)

          USE = .FALSE.
          DO 102 i = 1, MIN(NFIELD,MXFIELD_OVP)
            if ( SNLC_FIELD(ep).EQ.SNLC_FIELD_OVPLIST(i) ) USE=.TRUE.
 102      CONTINUE

          if ( .NOT. USE ) THEN
             NFIELD = NFIELD + 1
             IF ( NFIELD .LE. MXFIELD_OVP ) then
                SNLC_FIELD_OVPLIST(NFIELD) = SNLC_FIELD(ep)
                IDF_OVPLIST(NFIELD) = IDF
             ENDIF
          endif  ! end of USE
101   CONTINUE  ! ep loop


      IF ( NFIELD > MXFIELD_OVP ) THEN
         CALL PRINT_PREABORT_BANNER(FNAM(1:11)//char(0),20)

         DO  i = 1, MIN(NFIELD,MXFIELD_OVP)
            write(6,60) i, SNLC_FIELD_OVPLIST(i)
60          format(T5,'FIELD_OVPLIST(',I2,') = ', A)
         ENDDO

         write(c1err,61) NFIELD
         write(c2err,62) MXFIELD_OVP
 61      format('NFIELD_OVP = ', I3,' exceeds bound of')
 62      format('MXFIELD_OVP = ', I3 )
         CALL MADABORT(FNAM, c1err, c2err )
      ENDIF

      ISNLC_NFIELD_OVP = NFIELD

c prepare catenated string SNLC_FIELD_forC that is sorted based
c on survey fields.  e.g., if SURVEY_FIELDS = 'E1', 'E2' then
c SNLC_FIELDS = E2,E1 gets constructed as SNLC_FIELD_forC = 'E1+E2'

      SNLC_FIELDLIST = ''
      LENTOT = 0
      FIRST  = .TRUE.

      DO 300 i = 1, NFIELD_SURVEY
        FIELDTMP = SURVEY_FIELDNAME(i)  ! from SURVEY.DEF file
        LENTMP   = INDEX(FIELDTMP,' ')-1

        DO 301 ovp = 1, NFIELD  ! overlap fields in this SN
          L2 = INDEX(SNLC_FIELD_OVPLIST(ovp),' ')-1
          IF ( LENTMP .NE. L2 ) GOTO 301

          IF ( SNLC_FIELD_OVPLIST(ovp) .EQ. FIELDTMP ) THEN

             if ( FIRST ) then
               SNLC_FIELDLIST = FIELDTMP
               LENTOT = LENTOT + LENTMP
               FIRST  = .FALSE.
             else
                SNLC_FIELDLIST =
     &          SNLC_FIELDLIST(1:LENTOT) // '+' // FIELDTMP(1:LENTMP)
                LENTOT = LENTOT + LENTMP + 1
             endif

          ENDIF
 301    CONTINUE
 300  CONTINUE

      IF ( LENTOT .EQ. 0  ) THEN
         SNLC_FIELDLIST = 'VOID'
      ENDIF

      RETURN
      END   ! end COUNTFIELDS


C ========================================
CDECK  ID>,  U3BAND. 
      SUBROUTINE U3BAND()
c
c Created Sep 13, 2008 by R.Kessler
c
c Special flag to require exactly three passbands
c that pass the global SNRCUT, and one of the passbands
c must be U-band. If only two passbands exist, the SN
c is rejected. If 4 or more passbands exist, then the
c reddest extra passbands are erased and the SN is used.
c For example, if griz -> UBVR, then all z-band fluxes
c and errors are set to -9.0, and SNRECON is called
c again; this SN is then processed as if z-band had
c never existed.
c
c
c Jul 16, 2011: pass ISN as argument and remove IERR arg
c --------------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      INTEGER
     &   NBAND, NTMP
     &  ,IFILT, IFILT_OBS, IFILT_OBS_LIST(MXFILT_ALL)
     &  ,ORDER
     &  ,INDEX_SORT(MXFILT_ALL)
     &  ,i, isort
     &  ,NERASE

      REAL
     &   ZZ, RESTLAM
     &  ,RESTLAM_LIST(MXFILT_ALL)

      LOGICAL LSNRMAX, LU, LKEEP

      character cfilt*2, ccid*(MXCHAR_CCID), cdiscard*32

      REAL ULAMMAX
      PARAMETER ( ULAMMAX = 3900.0 ) ! max U-band lambda in rest-frame

      EXTERNAL SORTFLOAT

C ---------- BEGIN ---------

      NERASE = 0

      if ( .not. LTEST_U3BAND ) RETURN

      CCID = SNLC_CCID
      LKEEP = .TRUE.  ! keep SN by default

c require at least 3 passbands with SNRMAX cut.
c If not, set PEAKMJD = -9.0 and return so that
c this SN is rejected.

        NBAND = ISNLC_NFILT_SNRMAX
        IF ( NBAND .LT. 3 ) THEN
          LKEEP  = .FALSE.
          cdiscard = 'NBAND(SNRMAX) < 3'
          GOTO 150
        ENDIF

        ZZ          = 1.0  + SNLC_REDSHIFT


c filter loop: get list of observer passbands and check if
c U-band is there.

        NTMP = 0
        LU   = .FALSE.

        DO 101 ifilt = 1, NFILTDEF_SURVEY

           if ( .NOT. EXIST_FILT(ifilt) ) goto 101

           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)

           RESTLAM = FILTOBS_LAMAVG(ifilt_obs) / ZZ
           LSNRMAX = SNLC_SNRMAX_FILT(ifilt) .GT. CUTWIN_SNRMAX(1)

           if ( .NOT. LSNRMAX ) GOTO 101

           IF ( RESTLAM .LT. ULAMMAX .and.
     &          RESTLAM .GT. CUTWIN_RESTLAM(1) ) LU = .TRUE.

           NTMP = NTMP + 1
           IFILT_OBS_LIST(NTMP) = IFILT_OBS
           RESTLAM_LIST(NTMP)   = RESTLAM

101     CONTINUE  ! UFILT loop


        if ( .NOT. LU ) then
           LKEEP = .FALSE.
           cdiscard = 'No filter maps onto rest-U'
           goto 150
        endif

        if ( LU .and. NBAND .EQ. 3 ) GOTO 150

c here we have more than 3 bands with good SNRMAX.
c Erase reddest bands until we have the 3 bluest.

       ORDER = + 1 ! increasing order
       CALL SORTFLOAT( NBAND, RESTLAM_LIST, ORDER, INDEX_SORT)

c erase reddest filters as if they never existed
      DO i = 4, NTMP
        isort = INDEX_SORT(i)
        IFILT_OBS = IFILT_OBS_LIST(isort)
        cfilt = filtdef_string(ifilt_obs:ifilt_obs)
        RESTLAM   = RESTLAM_LIST(isort)

        write(6,440) CCID, cfilt, RESTLAM
440     format(T8,'U3BAND CID=',A8, ' : erase filter=',A,
     &       ' with rest-Lambda=',F6.0,' A' )

        NERASE =  NERASE + 1
        CALL ERASE_FILTER(ifilt_obs)
      ENDDO

c --------
150     CONTINUE
        IF ( .NOT. LKEEP ) THEN
          SNLC_SEARCH_PEAKMJD = -9.0
          write(6,441) CCID, cdiscard
441       format(T8,'U3BAND CID=',A8, ' => DISCARD because ', A )
        ENDIF

c ------------------------
c call SNRECON again after erasing filter(s)
      IF ( NERASE .GT. 0 ) THEN
        CALL SNRECON()
      ENDIF


      RETURN
      END


C ========================================
CDECK  ID>,  ERASEFLT. 
      SUBROUTINE ERASE_FILTER(ifilt_obs)
c
c Created Sep 13, 2008 by R.Kessler
c
c Erase "ifilt_obs" for SN index ISN.
c Erasing is done by setting fluxes and errors to -9.
c
c --------

      IMPLICIT NONE
      INTEGER IFILT_OBS   !(O) SN index, and filter index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK



      INTEGER NEWMJD, EPMIN, EPMAX, ep, ifilt

      LOGICAL LTMP

C -------- BEGIN -------

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

        DO EP = EPMIN, EPMAX

          LTMP = IFILT_OBS .EQ. ISNLC_IFILT_OBS(ep)

          IF ( LTMP ) THEN
            SNLC_FLUXCAL(ep)        = -9.0
            SNLC_FLUXCAL_ERRTOT(ep) = -9.0
            SNLC_MAG(ep)        = -9.0
            SNLC_ZEROPT(ep)     = -9.0
            SNLC_ZEROPT_ERR(ep) = -9.0

            IFILT  = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
            EXIST_FILT(ifilt)         = .FALSE.
            ISNLC_NEPOCH_FILT(ifilt)   =  0
            SNLC_SNRMAX_FILT(0)       = -9.
            SNLC_SNRMAX_FILT(ifilt)   = -9.
            SNLC_SNRMAX_SORT(ifilt)   = -9.
            SNLC_FLUXCALMAX(ifilt)    = -9.
            SNLC_FLUXCALMAX_ERR(ifilt)  = -9.

          ENDIF

        ENDDO

200   CONTINUE

      RETURN
      END

C =============================================
CDECK  ID>,  DLMAG8_REF. 
      DOUBLE PRECISION FUNCTION DLMAG8_REF(Z8)
      IMPLICIT NONE
c Oct 23 2020: refactor DLMAG function to use sntools_cosmology.c

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      REAL*8 Z8             ! input redshift
      REAL*8 zCMB, zHEL, vPEC, H0, OM, OL, w0, wa

      REAL*8   DLMAG_fortC    ! C function in sntools_cosmology.c
      EXTERNAL DLMAG_fortC

C ------- BEGIN -------

      H0   = H0_REF(1)
      OM   = OMAT_REF(1)
      OL   = OLAM_REF(1)
      w0   = W0_REF(1)
      wa   = DWDA_REF(1)
      zCMB = z8
      zHEL = z8
      vPEC = 0.0
      DLMAG8_REF = DLMAG_fortC(zCMB, zHEL, vPEC, H0, OM, OL, w0, wa)
      RETURN
      END           ! end DLMAG8_REF



C =============================
CDECK  ID>,  CCDNUMSTAT. 
      INTEGER FUNCTION CCDNUMSTAT(CCDNUM)
c
c Dec 2017
c Returns 0 if CCDNUM is valid; returns -1 otherwise.
c -------------------------

      IMPLICIT NONE

c function args

      INTEGER CCDNUM

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER i
      LOGICAL LCCDNUM

C -------------- BEGIN --------------

      IF ( NCCDNUM_LIST .LE. 0 ) THEN
         ! don't check  anything
         CCDNUMSTAT = 0
         RETURN
      ENDIF

      LCCDNUM = .FALSE.
      do i = 1, NCCDNUM_LIST
        if ( CCDNUM_LIST(i) .EQ. CCDNUM ) LCCDNUM = .TRUE.
      enddo


      IF ( LCCDNUM ) THEN
         CCDNUMSTAT   = 0
      ELSE
         CCDNUMSTAT = -1
      endif

      RETURN
      END  ! end CCDNUMSTAT


C ================================================
CDECK  ID>,  MAKE_SIMLIB_FILE. 
      SUBROUTINE MAKE_SIMLIB_FILE(OPT_FLAG)

c Created Feb 2016
c Create LIBID entry in simlib file, based on info from data file.
c Beware that event distribution is not necessarily uniform since
c it has the data distribution.
c
c OPT_FLAG = 1 --> open simlib file and write header
c OPT_FLAG = 2 --> add next LIBID
c OPT_FLAG = 3 --> close file
c
c  OPT_SIMLIB_OUT & 1 -> write SIM_MAGOBS for all obs,
c                        even for true flux = 0 and mag=99.
c  OPT_SIMLIB_OUT & 2 -> write SIM_MAGOBS only for true flux > 0
c
c
c Oct 15, 2019: fix format for SKYSIG : 6.2f -> 7.2f
c Nov 22, 2019: adapt to work on fakes and sims, and write MAG column.
c Oct 05, 2020: add ZP requirement to compute metadata; see FOUND_METADATA
c Jan 19, 2021: add pad space between MJD and IDEXPT
c Mar 26, 2021:
c   + suppress GALID since it wrote 12345 (garbage) for DC2
c   + skip LIBID of PEAKMJD < 1000
c
c --------------------------

      IMPLICIT NONE

      INTEGER OPT_FLAG ! 1=> init file, 2=> add simlib entry


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


c +CDE,SNANAFIT.

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SIMLIBCOM. inserted below by ypatchy. 

c Feb 2017: common block for writing SIMLIB file to SIMLIB_OUT

      INTEGER MXLIST_SKY
      PARAMETER ( MXLIST_SKY = 20)
      INTEGER  NLIST_SKY
      REAL*8   SKYLAM_LIST(MXLIST_SKY), SKYMAG_LIST(MXLIST_SKY)
      REAL*8   PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX

      LOGICAL ISGROUND, FOUND_TEMPLATE_INFO ! T=> ground based survey
      REAL
     &    SIMLIB_ZPERR(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_SKYSIG(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_ZPT(MXFILT_ALL)


      COMMON/SIMLIBCOM4/ NLIST_SKY, ISGROUND, FOUND_TEMPLATE_INFO
     &   ,SIMLIB_ZPERR
     &   ,SIMLIB_TEMPLATE_SKYSIG, SIMLIB_TEMPLATE_ZPT

      COMMON/SIMLIBCOM8/
     &   SKYLAM_LIST, SKYMAG_LIST
     &  ,PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX


c --- hard-wire ground based array of SKYMAG vs. lambda
c Apr 6 2020:
c  Add J,H,K from Table 3 of arxiv:0809.4988, and increase NLIST->10.
c  This CALAR ALTO paper doesn't have a table of mean filter wavelengths,
c  so we take <SKYLAM> from CSP JHK bands.

      INTEGER  NLIST_SKY_GROUND
      PARAMETER ( NLIST_SKY_GROUND = 10 )
      REAL*8 SKYLAM_GROUND_LIST(NLIST_SKY_GROUND)
      REAL*8 SKYMAG_GROUND_LIST(NLIST_SKY_GROUND)

c ugrizY mag/asec^2 are from LSST DEEP-drill cadence;
c v is made up to extend bluer.
      DATA SKYLAM_GROUND_LIST /
     &     2700.0, 3714.0, 4790.0, 6220.0,  ! v,u,g,r
     &     7544.0, 8679.0, 10095,           ! i,z,Y
     &     12500.0, 18900.0, 21500.  /      ! J,H,K (Apr 2020)
      DATA SKYMAG_GROUND_LIST /
     &     23.8, 22.7,  21.0,  20.4,    ! v,u,g,r
     &     19.4, 18.1,  17.9,           ! i,z,Y
     &     16.0, 14.0,  12.4  /         ! J,H,K (Apr 2020)

c --- hard-write space based array pf SKYMAG vs. lambda

      INTEGER  NLIST_SKY_SPACE
      PARAMETER ( NLIST_SKY_SPACE = 9 )
      REAL*8 SKYLAM_SPACE_LIST(NLIST_SKY_SPACE)
      REAL*8 SKYMAG_SPACE_LIST(NLIST_SKY_SPACE)

c from WFIRST sims
      DATA SKYLAM_SPACE_LIST /
     &        1000.0,  4330.0,  6258.0,  8052.0,          ! x,B,R,I
     &        8745.0, 10653.0, 12976.0, 15848.0, 20000. / ! Z,Y,J,H,FUDGE
      DATA SKYMAG_SPACE_LIST /
     &        23.5,    23.0,     22.3,   22.5,
     &        22.7,    22.6,     22.6,   22.7, 22.6  /


C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


      REAL*8  MJD, GAIN, RDNOISE, SKYSIG, PSF1, PSF2, PSFRAT
      REAL*8  ZP, ZPERR, MAG, FLUX, FLUXERR, PIXSIZE, LAMOBS
      REAL*8  MJD_MIN, TOBS_MIN, PEAKMJD, DVAL
      INTEGER LIBID, IFILT, IFILT_OBS, LASTEP(MXFILT_OBS)
      INTEGER LEN0, LEN1, LEN2, EPMIN, EPMAX, NEWMJD, NOBS, iep, EP
      INTEGER LENcMAG, ISTAT, LENF, NFILTDEF_TMP
      LOGICAL IS_REAL_DATA, WRALL_SIM_MAGOBS, WRSET_SIM_MAGOBS
      LOGICAL WR_SIM_MAGOBS, FOUND_METADATA
      CHARACTER BAND*4, FNAM*20, SEDCMD*200, cDUM*20, CCID*32
      CHARACTER cMAG*12, cNCUTS*12, STR_OLD*40, STR_NEW*60

C ------------------ BEGIN ------------------

      IF( SIMLIB_OUTFILE .EQ. '' ) RETURN

      FNAM = 'MAKE_SIMLIB_FILE'
      IS_REAL_DATA = ( .NOT. ISJOB_SIM )

c check option to write ALL SIM_MAGOBS, even for SIM_MAGOBS=99 where
c no fake or sim event was generated and there is zero flux.
      WRALL_SIM_MAGOBS =
     &    BTEST(OPT_SIMLIB_OUT,0) .and. (.not.IS_REAL_DATA)

c check option to write SIM_MAGOBS  only for true flux > 0
      WRSET_SIM_MAGOBS =
     &    BTEST(OPT_SIMLIB_OUT,1) .and. (.not.IS_REAL_DATA)
      WR_SIM_MAGOBS = WRALL_SIM_MAGOBS .or.  WRSET_SIM_MAGOBS

      NFILTDEF_TMP = NFILTDEF_OBS

c -------------------------------------------

      IF ( OPT_FLAG == 1 ) THEN



      C1ERR = 'Cannot use SIMLIB_OUT option with snlc_fit or psnid.'
      C2ERR = 'Use snana.exe instead. '
      CALL MADABORT(FNAM, c1err, c2err)

        GLOBAL_BANNER =
     &      'Prepare to write SIMLIB file from data'
        CALL PRBANNER (GLOBAL_BANNER(1:60) )
        LEN1 = INDEX(SIMLIB_OUTFILE,' ') -1
        print*,'   Open output SIMLIB file: ', SIMLIB_OUTFILE(1:LEN1)

        OPEN(   UNIT   = LUNOUT
     &        , FILE   = SIMLIB_OUTFILE
     &        , STATUS = 'UNKNOWN'         )

c - - - - - -
c write DOCANA

        WRITE(LUNOUT,20)  'DOCUMENTATION:'

        WRITE(LUNOUT,24)
     &       'PURPOSE: simulation cadence created from data'

        WRITE(LUNOUT,24)
     &       'VERSION_PHOTOMETRY: ' // VERSION_PHOTOMETRY(1)(1:60)

        WRITE(LUNOUT,24) 'NOTES: '
        WRITE(LUNOUT,24)
     &       '- Created from snana.exe using SIMLIB_OUTFILE option.'
        if ( WR_SIM_MAGOBS ) then
           WRITE(LUNOUT,24)
     &        '- SIM_MAGOBS are copied to MAG column.'
        endif

        WRITE(LUNOUT,20) 'DOCUMENTATION_END:'
        WRITE(LUNOUT,20) ' '

c - - - - - - - -
        LEN1 = INDEX(SURVEY_NAME,' ') - 1
        LEN2 = INDEX(SURVEY_FILTERS,' ') - 1
        WRITE(LUNOUT,10) 'SURVEY:      ',  SURVEY_NAME(1:LEN1)
        WRITE(LUNOUT,10) 'FILTERS:     ',  SURVEY_FILTERS(1:LEN2)
10      FORMAT(A, 1x, A)  ! KEY VAL

20      FORMAT(A)
24      FORMAT(T4,A)

        WRITE(LUNOUT,10) 'NLIBID:     ',  'NLIBID_REPLACE'

        if ( IS_REAL_DATA ) then
          WRITE(LUNOUT,10) 'PSF_UNIT:    ',  'ARCSEC_FWHM'
          WRITE(LUNOUT,10) 'SKYSIG_UNIT: ',  'ADU_PER_SQARCSEC'
          CALL SET_SIMLIB_SKYMAG()
          CALL SET_SIMLIB_ZPERR()
       endif

        WRITE(LUNOUT, '(/,A,/)' ) 'BEGIN LIBGEN'
cc90      FORMAT(/, 'BEGIN LIBGEN',/  )

        CALL FLUSH(LUNOUT)
        CALL FLUSH(6)

        RETURN
      ENDIF

      IF ( OPT_FLAG == 3 ) THEN
         write(LUNOUT,400)
400      format(/, 'END_OF_SIMLIB: ', / )
         close(UNIT = LUNOUT)

c replace N_SNLC_CUTS with comment giving number of SIMLIB entries
         write(cNCUTS,'(I6,2x)') N_SNLC_CUTS
         STR_OLD = 'NLIBID_REPLACE '
         STR_NEW = cNCUTS
         LEN0    = index(STR_OLD,' ') - 1
         LEN1    = 8    ! for cNCUT
         LEN2    = INDEX(SIMLIB_OUTFILE,' ') - 1
         write(SEDCMD,505)
     &       STR_OLD(1:LEN0), STR_NEW(1:LEN1), SIMLIB_OUTFILE(1:LEN2)
c        print*,' xxx SEDCMD = ', SEDCMD
         CALL SYSTEM(SEDCMD)

505      FORMAT('sed -i ', "'s/", A, '/',A, "/g1'", 2x, A)

c if SUBSURVEY_LIST is not blank, use system 'sed' command
c to insert its comma-separate list at top of SIMLIB file.
c fixed key SUBSURVEY_LIST to be printed after SURVEY key (M. Vincenzi Feb 2022)
         IF ( SUBSURVEY_NAME_LIST .NE. '' ) THEN
            LEN1   = INDEX(SUBSURVEY_NAME_LIST,' ') - 1
            LEN2   = INDEX(SIMLIB_OUTFILE,' ') - 1
            SEDCMD = "sed -i '/SURVEY:/a  SUBSURVEY_LIST: "
     &          // SUBSURVEY_NAME_LIST(1:LEN1) // "' "
     &          // SIMLIB_OUTFILE(1:LEN2)
            CALL SYSTEM(SEDCMD)
         ENDIF

         return
      ENDIF

C ------------- OPT_FLAG=2 below -------------------------

      IF ( ISNLC_NEWMJD_STORE < 4 ) RETURN
      IF ( SNLC_SEARCH_PEAKMJD < 1000.0 ) RETURN ! Mar 26 2021

      DO IFILT_OBS = 1, MXFILT_OBS
         LASTEP(IFILT_OBS) = -9
      ENDDO


c ----------
c first loop through and count NOBS
      NOBS = 0
      DO 25 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        DO 21 EP = EPMIN, EPMAX
           if ( WR_SIM_MAGOBS ) then
              MAG = SIM_EPMAGOBS(ep)
              if ( WRSET_SIM_MAGOBS .and. MAG > 98.0 ) goto 21
           endif
           NOBS = NOBS + 1
21     CONTINUE
25    CONTINUE

c -----------
      PIXSIZE = SNLC_PIXSIZE
      if ( PIXSIZE < 0.0 ) PIXSIZE = PIXSIZE_GUESS

      WRITE(LUNOUT,66)
66    FORMAT('#--------------------------------------------' )

c check option to force TMIN
      MJD_MIN  = SNLC8_MJD(1)
      PEAKMJD  = SNLC_SEARCH_PEAKMJD
      IF ( SIMLIB_OUT_TMINFIX < 999 ) THEN
        PEAKMJD = MJD_MIN - DBLE(SIMLIB_OUT_TMINFIX)
      ENDIF
      TOBS_MIN = MJD_MIN - PEAKMJD

      LIBID = SNLC_CID      ! UNIQUE_CIDINT(SNLC_CCID)

      WRITE(LUNOUT,101) LIBID, SNLC_CCID(1:ISNLC_LENCCID), TOBS_MIN
 101  FORMAT('LIBID: ', I8, 5x, '# cadence from SNID=', A, 2x,
     &    'min(MJD-PEAKMJD)=',F5.1  )

      WRITE(LUNOUT,103) SNLC8_RA, SNLC8_DEC, SNLC_MWEBV
 103  FORMAT('RA: ', F12.6, 8x, 'DEC:', F12.6, 5x, 'MWEBV: ',F7.4)

      WRITE(LUNOUT,105) NOBS, PIXSIZE,
     &       SNLC_REDSHIFT,  PEAKMJD
 105  FORMAT('NOBS: ', I4, 5x, 'PIXSIZE: ', F6.3, 5x,
     &       'REDSHIFT: 'F8.5, 5x, 'PEAKMJD: ', F9.3 )

      IF ( SUBSURVEY_NAME .NE. ' ' ) THEN
         WRITE(LUNOUT,10) 'SUBSURVEY:', SUBSURVEY_NAME
      ENDIF

c Nov 23 2019: add more info for simulated data
      IF ( WR_SIM_MAGOBS  ) THEN
cc          write(LUNOUT,"('GALID: ',I9)" ) SNHOST_OBJID(1)
         LENF = INDEX(SNLC_FIELDLIST,' ') - 1
         write(LUNOUT,"('FIELD: ',A )" ) SNLC_FIELDLIST(1:LENF) ! includes overlaps
      ENDIF

c - - - - - - - - - -

c - - - - -
      CALL SET_SIMLIB_TEMPLATE_INFO()  ! Feb 5 2020

      IF ( FOUND_TEMPLATE_INFO ) THEN
          write(LUNOUT,"('TEMPLATE_ZPT:',$)")
          DO ifilt = 1, NFILTDEF_SURVEY
             write(LUNOUT,"(F8.3,$)" ) SIMLIB_TEMPLATE_ZPT(ifilt)
          ENDDO
          write(LUNOUT,"(' ')")

          write(LUNOUT,"('TEMPLATE_SKYSIG:',$)")
          DO ifilt = 1, NFILTDEF_SURVEY
             write(LUNOUT,"(F9.2,$)" ) SIMLIB_TEMPLATE_SKYSIG(ifilt)
          ENDDO
          write(LUNOUT,"(' ')")

      ENDIF

c May 29 2020: write TAKE_SPECTRUM keys if there are spectra
      CALL WRITE_SIMLIB_TAKE_SPECTRUM(LUNOUT)

c write column header
      WRITE(LUNOUT,110)
110   FORMAT(/,'#   MJD    IDEXPT  BAND  GAIN RDNOISE  SKYSIG  ',
     &         'PSF1 PSF2 PSFRAT    ZP  ZPERR  MAG' )

      DO IFILT_OBS = 1, MXFILT_OBS
         LASTEP(IFILT_OBS) = -9
      ENDDO

c --------
      DO 300 NEWMJD = 1, ISNLC_NEWMJD_STORE

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)

        DO 301 IEP = EPMIN, EPMAX

           EP        = IEP
           MJD       = SNLC8_MJD(EP)
           IFILT_OBS = ISNLC_IFILT_OBS(ep)
           IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
           BAND      = FILTDEF_STRING(ifilt_obs:ifilt_obs)

           if ( EP < 0 ) goto 301  ! nothing valid to print

           GAIN      = SNGL( SNLC_GAIN(ep) )
           RDNOISE   = SNGL( SNLC_RDNOISE(ep) )
           SKYSIG    = SNGL( SNLC_SKYSIG(ep) )
           PSF1      = SNGL( SNLC_PSF_SIG1(ep) )
           PSF2      = SNGL( SNLC_PSF_SIG2(ep) )
           PSFRAT    = SNGL( SNLC_PSF_RATIO(ep) )
           ZP        = SNGL( SNLC_ZEROPT(ep) )
           ZPERR     = SNGL( SNLC_ZEROPT_ERR(ep) )

           cMAG      = '99' ; LENcMAG=2
           if ( WR_SIM_MAGOBS ) then
              MAG = SIM_EPMAGOBS(ep)
              if ( WRSET_SIM_MAGOBS .and. MAG > 98.0 ) goto 301
              write(cMAG,"(F8.4)") MAG
              LENcMAG = 8
           endif

           IF ( PSF1 < 1.0E-5 .and. SKYSIG > 1.0E-5 ) GOTO 301

c if simlib info is not available, estimate it from FLUX and FLUXERR.
c Mainly for low-z sample which has no meta data.

           FOUND_METADATA =
     &       ( PSF1 > 1.0E-5 .and. SKYSIG > 1.0E-5 .and. ZP > 1.0)

           IF ( .not. FOUND_METADATA ) THEN
              GAIN    = 1.0 ;  RDNOISE = 1.0
              ZPERR   = DBLE( SIMLIB_ZPERR(ifilt_obs) )
              PSF2    = 0.0 ;  PSFRAT  = 0.0
              FLUX    = SNLC_FLUXCAL(EP)
              FLUXERR = SNLC_FLUXCAL_ERRTOT(EP)
              LAMOBS  = FILTOBS_LAMAVG(IFILT_OBS)

              if ( LAMOBS < 0.0 ) then
                 c1err = 'Invalid/undefined band = ' // band
                 c2err = 'Make sure all bands are defined in kcor file'
                 CALL MADABORT(FNAM, C1ERR, C2ERR )
              endif
              CALL COMPUTE_SIMLIB_INFO(
     &               SNLC_CCID,FLUX,FLUXERR,LAMOBS,PIXSIZE,
     &               PSF1, SKYSIG, ZP)     ! returned
           ENDIF

           write(LUNOUT,120)
     &        MJD, EP, BAND,    ! EP is a dummy ID
     &        GAIN, RDNOISE,
     &        SKYSIG, PSF1, PSF2, PSFRAT,
     &        ZP, ZPERR, cMAG(1:LENcMAG)

120        format('S: ',
     &            F9.3, 1x, I4, 2x, A2, 2x,  ! MJD, ID, BAND
     &            F5.2, 2x, F5.2, 2x,        ! GAIN, RDNOISE
     &            F7.2, 1x, 3(F6.2),2x,      ! SKYSIG, PSF info
     &            F6.3, 1x, F5.3, 1x, A      ! ZP, ZPERR, MAG
     &                )

301   CONTINUE
300   CONTINUE

      WRITE(LUNOUT,199) SNLC_CID
199   FORMAT('END_LIBID: ', I8, / )
      CALL FLUSH(6)

      RETURN
      END  ! end of MAKE_SIMLIB_FILE


C =========================================
CDECK  ID>,  SET_SIMLIB_TEMPLATE_INFO. 
      SUBROUTINE SET_SIMLIB_TEMPLATE_INFO()

c Created Feb 2020
c If there is SKYSIG_T (template) info, set arrays
c    SIMLIB_TEMPLATE_ZPT[SKYSIG](ifilt)
c Search all epochs and extract typical epoch for each band.
c
c Mar 26 2021: require SKYSIG_T > 0

      IMPLICIT NONE

c local variables


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SIMLIBCOM. inserted below by ypatchy. 

c Feb 2017: common block for writing SIMLIB file to SIMLIB_OUT

      INTEGER MXLIST_SKY
      PARAMETER ( MXLIST_SKY = 20)
      INTEGER  NLIST_SKY
      REAL*8   SKYLAM_LIST(MXLIST_SKY), SKYMAG_LIST(MXLIST_SKY)
      REAL*8   PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX

      LOGICAL ISGROUND, FOUND_TEMPLATE_INFO ! T=> ground based survey
      REAL
     &    SIMLIB_ZPERR(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_SKYSIG(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_ZPT(MXFILT_ALL)


      COMMON/SIMLIBCOM4/ NLIST_SKY, ISGROUND, FOUND_TEMPLATE_INFO
     &   ,SIMLIB_ZPERR
     &   ,SIMLIB_TEMPLATE_SKYSIG, SIMLIB_TEMPLATE_ZPT

      COMMON/SIMLIBCOM8/
     &   SKYLAM_LIST, SKYMAG_LIST
     &  ,PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX


c --- hard-wire ground based array of SKYMAG vs. lambda
c Apr 6 2020:
c  Add J,H,K from Table 3 of arxiv:0809.4988, and increase NLIST->10.
c  This CALAR ALTO paper doesn't have a table of mean filter wavelengths,
c  so we take <SKYLAM> from CSP JHK bands.

      INTEGER  NLIST_SKY_GROUND
      PARAMETER ( NLIST_SKY_GROUND = 10 )
      REAL*8 SKYLAM_GROUND_LIST(NLIST_SKY_GROUND)
      REAL*8 SKYMAG_GROUND_LIST(NLIST_SKY_GROUND)

c ugrizY mag/asec^2 are from LSST DEEP-drill cadence;
c v is made up to extend bluer.
      DATA SKYLAM_GROUND_LIST /
     &     2700.0, 3714.0, 4790.0, 6220.0,  ! v,u,g,r
     &     7544.0, 8679.0, 10095,           ! i,z,Y
     &     12500.0, 18900.0, 21500.  /      ! J,H,K (Apr 2020)
      DATA SKYMAG_GROUND_LIST /
     &     23.8, 22.7,  21.0,  20.4,    ! v,u,g,r
     &     19.4, 18.1,  17.9,           ! i,z,Y
     &     16.0, 14.0,  12.4  /         ! J,H,K (Apr 2020)

c --- hard-write space based array pf SKYMAG vs. lambda

      INTEGER  NLIST_SKY_SPACE
      PARAMETER ( NLIST_SKY_SPACE = 9 )
      REAL*8 SKYLAM_SPACE_LIST(NLIST_SKY_SPACE)
      REAL*8 SKYMAG_SPACE_LIST(NLIST_SKY_SPACE)

c from WFIRST sims
      DATA SKYLAM_SPACE_LIST /
     &        1000.0,  4330.0,  6258.0,  8052.0,          ! x,B,R,I
     &        8745.0, 10653.0, 12976.0, 15848.0, 20000. / ! Z,Y,J,H,FUDGE
      DATA SKYMAG_SPACE_LIST /
     &        23.5,    23.0,     22.3,   22.5,
     &        22.7,    22.6,     22.6,   22.7, 22.6  /


      INTEGER ep, EPMIN, EPMAX, NEWMJD, IFILT, IFILT_OBS
      LOGICAL IS_SET(MXFILT_ALL), LZPT, LSKY
      REAL ZPT, SKYSIG

C ------------- BEGIN -------------

      DO IFILT = 1, NFILTDEF_SURVEY
        SIMLIB_TEMPLATE_ZPT(ifilt)    =  0.0
        SIMLIB_TEMPLATE_SKYSIG(ifilt) =  0.0
        IS_SET(IFILT) = .FALSE.
      END DO


      FOUND_TEMPLATE_INFO = .FALSE.

c find first epoch for each band

      DO 300 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        DO 301 EP = EPMIN, EPMAX
           IFILT_OBS = ISNLC_IFILT_OBS(ep)
           IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
           ZPT       = SNLC_ZEROPT(ep)
           SKYSIG    = SNLC_SKYSIG_T(ep)
           LZPT      = (ZPT > 10.0)
           LSKY      = SKYSIG > 0.001
           if ( .not.IS_SET(ifilt) .and. LZPT .and. LSKY) then
             IS_SET(ifilt)                 = .TRUE.
             FOUND_TEMPLATE_INFO           = .TRUE.
             SIMLIB_TEMPLATE_ZPT(ifilt)    = ZPT
             SIMLIB_TEMPLATE_SKYSIG(ifilt) = SKYSIG
           endif
 301    CONTINUE
 300  CONTINUE

      RETURN
      END

C ====================================
CDECK  ID>,  SET_SIMLIB_SKYMAG. 
      SUBROUTINE SET_SIMLIB_SKYMAG()

c Check SURVEY_NAME for space or ground missing;
c set SKYMAG_LIST and PSF_FWHM accordingly.
c Beware that list of space surveys is hard-wired.

      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SIMLIBCOM. inserted below by ypatchy. 

c Feb 2017: common block for writing SIMLIB file to SIMLIB_OUT

      INTEGER MXLIST_SKY
      PARAMETER ( MXLIST_SKY = 20)
      INTEGER  NLIST_SKY
      REAL*8   SKYLAM_LIST(MXLIST_SKY), SKYMAG_LIST(MXLIST_SKY)
      REAL*8   PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX

      LOGICAL ISGROUND, FOUND_TEMPLATE_INFO ! T=> ground based survey
      REAL
     &    SIMLIB_ZPERR(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_SKYSIG(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_ZPT(MXFILT_ALL)


      COMMON/SIMLIBCOM4/ NLIST_SKY, ISGROUND, FOUND_TEMPLATE_INFO
     &   ,SIMLIB_ZPERR
     &   ,SIMLIB_TEMPLATE_SKYSIG, SIMLIB_TEMPLATE_ZPT

      COMMON/SIMLIBCOM8/
     &   SKYLAM_LIST, SKYMAG_LIST
     &  ,PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX


c --- hard-wire ground based array of SKYMAG vs. lambda
c Apr 6 2020:
c  Add J,H,K from Table 3 of arxiv:0809.4988, and increase NLIST->10.
c  This CALAR ALTO paper doesn't have a table of mean filter wavelengths,
c  so we take <SKYLAM> from CSP JHK bands.

      INTEGER  NLIST_SKY_GROUND
      PARAMETER ( NLIST_SKY_GROUND = 10 )
      REAL*8 SKYLAM_GROUND_LIST(NLIST_SKY_GROUND)
      REAL*8 SKYMAG_GROUND_LIST(NLIST_SKY_GROUND)

c ugrizY mag/asec^2 are from LSST DEEP-drill cadence;
c v is made up to extend bluer.
      DATA SKYLAM_GROUND_LIST /
     &     2700.0, 3714.0, 4790.0, 6220.0,  ! v,u,g,r
     &     7544.0, 8679.0, 10095,           ! i,z,Y
     &     12500.0, 18900.0, 21500.  /      ! J,H,K (Apr 2020)
      DATA SKYMAG_GROUND_LIST /
     &     23.8, 22.7,  21.0,  20.4,    ! v,u,g,r
     &     19.4, 18.1,  17.9,           ! i,z,Y
     &     16.0, 14.0,  12.4  /         ! J,H,K (Apr 2020)

c --- hard-write space based array pf SKYMAG vs. lambda

      INTEGER  NLIST_SKY_SPACE
      PARAMETER ( NLIST_SKY_SPACE = 9 )
      REAL*8 SKYLAM_SPACE_LIST(NLIST_SKY_SPACE)
      REAL*8 SKYMAG_SPACE_LIST(NLIST_SKY_SPACE)

c from WFIRST sims
      DATA SKYLAM_SPACE_LIST /
     &        1000.0,  4330.0,  6258.0,  8052.0,          ! x,B,R,I
     &        8745.0, 10653.0, 12976.0, 15848.0, 20000. / ! Z,Y,J,H,FUDGE
      DATA SKYMAG_SPACE_LIST /
     &        23.5,    23.0,     22.3,   22.5,
     &        22.7,    22.6,     22.6,   22.7, 22.6  /


      INTEGER i, LENS

C -------------- BEGIN --------------

      ISGROUND = .TRUE.  ! default
      IF ( INDEX(SURVEY_NAME,'HST'     ) > 0 ) ISGROUND = .FALSE.
      IF ( INDEX(SURVEY_NAME,'JWST'    ) > 0 ) ISGROUND = .FALSE.
      IF ( INDEX(SURVEY_NAME,'WFIRST'  ) > 0 ) ISGROUND = .FALSE.
      IF ( INDEX(SURVEY_NAME,'CANDELS' ) > 0 ) ISGROUND = .FALSE.

      LENS = INDEX(SURVEY_NAME,' ') - 1

      IF ( ISGROUND ) THEN
          write(6,20) SURVEY_NAME(1:LENS), 'GROUND'
          NLIST_SKY = NLIST_SKY_GROUND
          DO i = 1, NLIST_SKY_GROUND
            SKYLAM_LIST(i) = SKYLAM_GROUND_LIST(i)
            SKYMAG_LIST(i) = SKYMAG_GROUND_LIST(i)
          ENDDO
          PSF_FWHM_GUESS   = 1.0   ! arcSec
          PIXSIZE_GUESS    = 0.5   ! arcSec
          ADD_SKYSIG_PIX   = 0.05  ! skySigma per pixel to add in loop

      ELSE
          write(6,20) SURVEY_NAME(1:LENS), 'SPACE'
          NLIST_SKY = NLIST_SKY_SPACE
          DO i = 1, NLIST_SKY_SPACE
            SKYLAM_LIST(i) = SKYLAM_SPACE_LIST(i)
            SKYMAG_LIST(i) = SKYMAG_SPACE_LIST(i)
          ENDDO
          PSF_FWHM_GUESS   = 0.2  ! arcSec
          PIXSIZE_GUESS    = 0.1
          ADD_SKYSIG_PIX   = 0.01
      ENDIF

20    format(T5,'Survey ',A, ' --> ', A, ' instrument params.' )
      write(6,40) 'PSF_FWHM ' , PSF_FWHM_GUESS, 'arcSeconds'
      write(6,40) 'PIXSIZE  ' , PIXSIZE_GUESS, 'arcSeconds'
40    format(T10, 'Set ', A,' = ', F6.3, 2x, A )

      DO i = 1, NLIST_SKY
         write(6,50) SKYLAM_LIST(i), SKYMAG_LIST(i)
50       format(T10, 'Set SKYMAG(',F7.0,' A) = ', F5.2, ' / asec^2'  )
      ENDDO

c - - - - - -
c Write info to SIMLIB file
      if ( ISGROUND ) then
         write(LUNOUT,11) 'GROUND'
      else
         write(LUNOUT,11) 'SPACE'
      endif
11      format(/, '# Assume instrument parameters for ', A)
        DO i = 1, NLIST_SKY
           write(LUNOUT,12) SKYLAM_LIST(i), SKYMAG_LIST(i)
12         format('# Assume SKYMAG(',F7.0,') = ', F5.2,' mag/asec^2')
        ENDDO

      RETURN
      END     ! end SET_SIMLIB_SKYMAG

C ====================================
CDECK  ID>,  SET_SIMLIB_ZPERR. 
      SUBROUTINE SET_SIMLIB_ZPERR()

c Set SIMLIB_ZPERR(ifilt_obs) using &SNLCINP input
c   SIMLIB_ZPERR_LIST = 'abc .01 def .02 hij .014'
c
c If SIMLIB_ZPERR_LIST='', set all ZPERR = 0.01
c

      IMPLICIT NONE
c +CDE,SNPAR.
c +CDE,CTRLCOM.

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SIMLIBCOM. inserted below by ypatchy. 

c Feb 2017: common block for writing SIMLIB file to SIMLIB_OUT

      INTEGER MXLIST_SKY
      PARAMETER ( MXLIST_SKY = 20)
      INTEGER  NLIST_SKY
      REAL*8   SKYLAM_LIST(MXLIST_SKY), SKYMAG_LIST(MXLIST_SKY)
      REAL*8   PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX

      LOGICAL ISGROUND, FOUND_TEMPLATE_INFO ! T=> ground based survey
      REAL
     &    SIMLIB_ZPERR(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_SKYSIG(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_ZPT(MXFILT_ALL)


      COMMON/SIMLIBCOM4/ NLIST_SKY, ISGROUND, FOUND_TEMPLATE_INFO
     &   ,SIMLIB_ZPERR
     &   ,SIMLIB_TEMPLATE_SKYSIG, SIMLIB_TEMPLATE_ZPT

      COMMON/SIMLIBCOM8/
     &   SKYLAM_LIST, SKYMAG_LIST
     &  ,PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX


c --- hard-wire ground based array of SKYMAG vs. lambda
c Apr 6 2020:
c  Add J,H,K from Table 3 of arxiv:0809.4988, and increase NLIST->10.
c  This CALAR ALTO paper doesn't have a table of mean filter wavelengths,
c  so we take <SKYLAM> from CSP JHK bands.

      INTEGER  NLIST_SKY_GROUND
      PARAMETER ( NLIST_SKY_GROUND = 10 )
      REAL*8 SKYLAM_GROUND_LIST(NLIST_SKY_GROUND)
      REAL*8 SKYMAG_GROUND_LIST(NLIST_SKY_GROUND)

c ugrizY mag/asec^2 are from LSST DEEP-drill cadence;
c v is made up to extend bluer.
      DATA SKYLAM_GROUND_LIST /
     &     2700.0, 3714.0, 4790.0, 6220.0,  ! v,u,g,r
     &     7544.0, 8679.0, 10095,           ! i,z,Y
     &     12500.0, 18900.0, 21500.  /      ! J,H,K (Apr 2020)
      DATA SKYMAG_GROUND_LIST /
     &     23.8, 22.7,  21.0,  20.4,    ! v,u,g,r
     &     19.4, 18.1,  17.9,           ! i,z,Y
     &     16.0, 14.0,  12.4  /         ! J,H,K (Apr 2020)

c --- hard-write space based array pf SKYMAG vs. lambda

      INTEGER  NLIST_SKY_SPACE
      PARAMETER ( NLIST_SKY_SPACE = 9 )
      REAL*8 SKYLAM_SPACE_LIST(NLIST_SKY_SPACE)
      REAL*8 SKYMAG_SPACE_LIST(NLIST_SKY_SPACE)

c from WFIRST sims
      DATA SKYLAM_SPACE_LIST /
     &        1000.0,  4330.0,  6258.0,  8052.0,          ! x,B,R,I
     &        8745.0, 10653.0, 12976.0, 15848.0, 20000. / ! Z,Y,J,H,FUDGE
      DATA SKYMAG_SPACE_LIST /
     &        23.5,    23.0,     22.3,   22.5,
     &        22.7,    22.6,     22.6,   22.7, 22.6  /


C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER ifilt, IFILTDEF, NF, iafilt(MXFILT_OBS)
      REAL xafilt(MXFILT_OBS), ZPERR

C -------------- BEGIN --------------

      DO IFILT = 1, MXFILT_ALL
        SIMLIB_ZPERR(IFILT) = 0.01  ! default
      ENDDO

      IF ( SIMLIB_ZPERR_LIST .EQ. '' ) RETURN

      CALL PARSE_FILTSTRING(0, SIMLIB_ZPERR_LIST, NF,iafilt,xafilt)
      DO ifilt    = 1, NF
         ifiltdef = IAFILT(ifilt)
         ZPERR    = xafilt(ifilt)
         SIMLIB_ZPERR(ifiltdef) = ZPERR
      ENDDO

      RETURN
      END   ! ene SET_SIMLIB_ZPERR


C =======================================================
CDECK  ID>,  COMPUTE_SIMLIB_INFO. 
      SUBROUTINE COMPUTE_SIMLIB_INFO(CCID,FLUX,FLUXERR,LAMOBS,PIXSIZE,
     &                               PSF,SKYSIG,ZP)

c
c Created Jan 26 2017 by R.Kessler
c When &SNLCINP namelist SIMLIB_OUTFILE is specified (fileName),
c and the data files have no meta data, this function is called
c as a hack to compute SIMLIB row entries for PSF, SKYSIG and ZP.
c
c Strategy here is numerical solution with assumptions on
c the PSF and sky brightness. Maybe can be done analytically,
c but I didn't try.

c * Fix PSF.
c * assume a sky brightness vs. wavelength estimate from LSST
c     deep-drill cadence. Interpolate SKYMAG_REF based on
c     input LAMOBS = central wavelength of filter.
c * loop over grid of SKYSIG values, increments of 0.1
c * for each SKYSIG, SNR_meas = Fpe/sqrt(Fpe+SQSKYSG) is solved
c    (quadratic equation) for ZP(pe) between FLUXCAL and MAG.
c * Use ZP and SKYSIG to compute "SKYMAG_predict"
c * SKYSIG with smallest |SKYMAG_predict - SKYMAG_REF|
c    is the result.
c
c Something similar was previously done for the low-z similb
c using only CFA3_KEPLERCAM; the resulting CFA3_KEPLERCAM.SIMLIB
c was used to simulate low-z in
c    http://adsabs.harvard.edu/abs/2013ApJ...764...48K
c and also in the JLA(Betoule 2014) and PS1(Sconlic 2014)
c analyses.
c Unfortunately, I cannot find the script or used to create
c CFA3_KEPLERCAM.SIMLIB .
c
c ----------------------------------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SIMLIBCOM. inserted below by ypatchy. 

c Feb 2017: common block for writing SIMLIB file to SIMLIB_OUT

      INTEGER MXLIST_SKY
      PARAMETER ( MXLIST_SKY = 20)
      INTEGER  NLIST_SKY
      REAL*8   SKYLAM_LIST(MXLIST_SKY), SKYMAG_LIST(MXLIST_SKY)
      REAL*8   PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX

      LOGICAL ISGROUND, FOUND_TEMPLATE_INFO ! T=> ground based survey
      REAL
     &    SIMLIB_ZPERR(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_SKYSIG(MXFILT_ALL)
     &   ,SIMLIB_TEMPLATE_ZPT(MXFILT_ALL)


      COMMON/SIMLIBCOM4/ NLIST_SKY, ISGROUND, FOUND_TEMPLATE_INFO
     &   ,SIMLIB_ZPERR
     &   ,SIMLIB_TEMPLATE_SKYSIG, SIMLIB_TEMPLATE_ZPT

      COMMON/SIMLIBCOM8/
     &   SKYLAM_LIST, SKYMAG_LIST
     &  ,PSF_FWHM_GUESS, PIXSIZE_GUESS, ADD_SKYSIG_PIX


c --- hard-wire ground based array of SKYMAG vs. lambda
c Apr 6 2020:
c  Add J,H,K from Table 3 of arxiv:0809.4988, and increase NLIST->10.
c  This CALAR ALTO paper doesn't have a table of mean filter wavelengths,
c  so we take <SKYLAM> from CSP JHK bands.

      INTEGER  NLIST_SKY_GROUND
      PARAMETER ( NLIST_SKY_GROUND = 10 )
      REAL*8 SKYLAM_GROUND_LIST(NLIST_SKY_GROUND)
      REAL*8 SKYMAG_GROUND_LIST(NLIST_SKY_GROUND)

c ugrizY mag/asec^2 are from LSST DEEP-drill cadence;
c v is made up to extend bluer.
      DATA SKYLAM_GROUND_LIST /
     &     2700.0, 3714.0, 4790.0, 6220.0,  ! v,u,g,r
     &     7544.0, 8679.0, 10095,           ! i,z,Y
     &     12500.0, 18900.0, 21500.  /      ! J,H,K (Apr 2020)
      DATA SKYMAG_GROUND_LIST /
     &     23.8, 22.7,  21.0,  20.4,    ! v,u,g,r
     &     19.4, 18.1,  17.9,           ! i,z,Y
     &     16.0, 14.0,  12.4  /         ! J,H,K (Apr 2020)

c --- hard-write space based array pf SKYMAG vs. lambda

      INTEGER  NLIST_SKY_SPACE
      PARAMETER ( NLIST_SKY_SPACE = 9 )
      REAL*8 SKYLAM_SPACE_LIST(NLIST_SKY_SPACE)
      REAL*8 SKYMAG_SPACE_LIST(NLIST_SKY_SPACE)

c from WFIRST sims
      DATA SKYLAM_SPACE_LIST /
     &        1000.0,  4330.0,  6258.0,  8052.0,          ! x,B,R,I
     &        8745.0, 10653.0, 12976.0, 15848.0, 20000. / ! Z,Y,J,H,FUDGE
      DATA SKYMAG_SPACE_LIST /
     &        23.5,    23.0,     22.3,   22.5,
     &        22.7,    22.6,     22.6,   22.7, 22.6  /


C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


c subroutine args
      CHARACTER CCID*(MXCHAR_CCID)  ! (I) for error message only

      DOUBLE PRECISION
     &   FLUX              ! (I) FLUXCAL
     &  ,FLUXERR           ! (I) error on above
     &  ,LAMOBS            ! (I) central wavelength of filter
     &  ,PIXSIZE           ! (I) pixel size, arcsec
     &  ,PSF, SKYSIG, ZP   ! (O)


c local args
      INTEGER NLOOP, MXLOOP
      REAL*8
     &   PSF_SIG, SKYMAG, TMP_SKYMAG
     &  ,TMP_SKYSIG_PIX, TMP_SKYSIG_ASEC, TMP_SQSKYSIG_TOT
     &  ,TMP_ZP, TMP_Fsky_pix,  TMP_FSKY_ASEC, TMP_Fpe
     &  ,SNR, SQSNR, NEA, MAG, MAG_MAX,  ARG, AREA_PIXEL
     &  ,SKYMAGDIF, SKYMAGDIF_MIN, SKYMAGDIF_LAST, SNR_CHECK

      CHARACTER FNAM*20, C1ERR*80, C2ERR*80

      REAL*8   INTERP_1DFUN
      EXTERNAL INTERP_1DFUN

      LOGICAL LDMP

C --------------- BEGIN ---------------

c init output
      PSF = 0.0; SKYSIG=0.0 ; ZP=0.0

c      LDMP = .TRUE.
      LDMP = .FALSE.

      FNAM = 'COMPUTE_SIMLIB_INFO'

c set MAG_MAX based on Flux = FluxErr
      MAG_MAX = ZEROPOINT_FLUXCAL_DEFAULT - 2.5*LOG10(FLUXERR)
      if ( FLUX > FLUXERR ) then
         MAG = ZEROPOINT_FLUXCAL_DEFAULT - 2.5*LOG10(FLUX)
      else
         MAG = MAG_MAX
      endif

c abort on insane FLUXERR
      IF ( FLUXERR < 1.0E-8 ) THEN
         write(c1err,161) 'FLUXERR', FLUXERR, FLUX
161      format('Insane ', A,' value = ', F12.4,
     &         3x, 'for FLUX=',F12.4)
         c2err = 'Check CID = ' // CCID
         CALL MADABORT(FNAM, c1err, c2err)
      ENDIF

c hard-wire PSF since we can't solve for all 3 items
      PSF      = PSF_FWHM_GUESS         ! set output
      PSF_SIG  = PSF_FWHM_GUESS/2.355   ! PSF in sigma, arcsec
      NEA      = 4.0*PI * (PSF_SIG*PSF_SIG)  ! Noise-equiv area, arcSec^2
      AREA_PIXEL = PIXSIZE**2     ! area of 1 pixel, arcsec^2

      SQSNR = (FLUX**2) / ( FLUXERR**2 + (0.0*FLUX)**2 )
      IF ( SQSNR < 2.0 ) SQSNR = 2.0  ! protect crazy SIMLIB values
      SNR   = sqrt(SQSNR)
      SKYMAGDIF_MIN = 9999.

c linear interpolation to get estimate of Sky mag per asec^2
      SKYMAG = interp_1dfun(1, LAMOBS, NLIST_SKY,
     &                  SKYLAM_LIST, SKYMAG_LIST,
     &                  FNAM//char(0), 20)

      IF ( LDMP ) THEN
        print*,' xxx --------------------------------- '
        print*,' xxx FLUX = ', sngl(FLUX), ' +- ', sngl(FLUXERR)
        print*,' xxx LAMOBS, SKYMAG = ', sngl(LAMOBS), sngl(SKYMAG)
        print*,' xxx NEA  = ', sngl(NEA)
        print*,' xxx PSF  = ', sngl(PSF_FWHM_GUESS), ' FWHM '
        print*,' xxx SNR  = ', sngl(SNR)
        print*,' xxx AREA_PIXEL = ', sngl(AREA_PIXEL)
      ENDIF

      SKYMAGDIF_LAST = 9999; SKYMAGDIF = 999. ;
      TMP_SKYSIG_PIX = ADD_SKYSIG_PIX
      NLOOP = 0 ; MXLOOP = 100000

      DO WHILE ( SKYMAGDIF < SKYMAGDIF_LAST )
         NLOOP = NLOOP + 1
         SKYMAGDIF_LAST   = SKYMAGDIF

c  increment skysig (pe) per pix
         TMP_SKYSIG_PIX   = TMP_SKYSIG_PIX + ADD_SKYSIG_PIX
         TMP_SKYSIG_ASEC  = TMP_SKYSIG_PIX / PIXSIZE  ! sqrt(AREA_PIXEL)

         TMP_SQSKYSIG_TOT = NEA * (TMP_SKYSIG_ASEC**2) ! total SQSKYSIG
         TMP_FSKY_PIX     = TMP_SKYSIG_PIX**2         ! sky val/pix, pe
         TMP_FSKY_ASEC    = TMP_FSKY_PIX / AREA_PIXEL ! sky val/asec^2

         ARG           = 1.0 + 4.0 * TMP_SQSKYSIG_TOT / SQSNR
         TMP_Fpe       = (SQSNR/2.0) * ( 1.0 + sqrt(ARG) )
         TMP_ZP        = MAG + 2.5*LOG10(TMP_Fpe)

c check how close computed TMP_SKYMAG is to expected SKYMAG
         TMP_SKYMAG    = TMP_ZP - 2.5*log10(TMP_FSKY_ASEC)
         SKYMAGDIF     = abs(TMP_SKYMAG - SKYMAG)

         if ( SKYMAGDIF < SKYMAGDIF_MIN ) then
            SKYMAGDIF_MIN = SKYMAGDIF
            SKYSIG    = TMP_SKYSIG_PIX/PIXSIZE     ! per arcSec^2
            ZP        = TMP_ZP                     ! pe per exposure
         endif

         IF ( NLOOP > MXLOOP ) THEN
            CALL PRINT_PREABORT_BANNER(FNAM(1:18)//char(0),40)
            print*,'   FLUX = ', sngl(FLUX), ' +- ', sngl(FLUXERR)
            print*,'   LAMOBS, SKYMAG = ', sngl(LAMOBS), sngl(SKYMAG)
            print*,'   NEA  = ', sngl(NEA)
            print*,'   PSF  = ', sngl(PSF_FWHM_GUESS), ' FWHM '
            print*,'   SNR  = ', sngl(SNR)
            print*,'   AREA_PIXEL = ', sngl(AREA_PIXEL)
            print*,'   NLOOP = ', NLOOP
            print*,'   last SKYSIG = ', sngl(TMP_SKYSIG_PIX/PIXSIZE)
            print*,'   last ZP     = ', sngl(TMP_ZP)
            C1ERR = 'Cannot determine SKYSIG '
            C2ERR = 'after NLOOP tries '
            CALL MADABORT(FNAM, c1err, c2err)
         ENDIF

         IF ( LDMP ) THEN
            SNR_CHECK = TMP_Fpe / sqrt(TMP_Fpe + TMP_SQSKYSIG_TOT )
           write(6,60) NLOOP, TMP_SKYSIG_PIX, SKYMAGDIF, SNR_CHECK/SNR
60         format(' xxx ', I3,' SkySig=',F5.2, 5x, 'SKYMAGDIF=',F8.5,
     &         5x,'SNR(test)=',F6.4 )
         ENDIF
      ENDDO

      IF ( LDMP ) THEN
        print*,' xxx FINAL PSF,SKYSIG,ZP = ',
     &       sngl(PSF), sngl(SKYSIG), sngl(ZP)
          print*,' xxx DEBUG STOP' ; CALL FLUSH(6)
          CALL EXIT(EXIT_ERRCODE)
      ENDIF

      RETURN
      END      ! end COMPUTE_SIMLIB_INFO

C ==================
CDECK  ID>,  WRITE_SIMLIB_SPECTRUM. 
      SUBROUTINE WRITE_SIMLIB_TAKE_SPECTRUM(LUN)

C Created May 29 2020
C If there are spectra, write TAKE_SPECTRUM keys to
C SIMLIB header (LUNOUT)
C

      IMPLICIT NONE
      INTEGER LUN ! (I) write to this LUN


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


c discard if FLUXERR/FLUXERR_MEDIAN exceeds this value
c --> avoid crazy large errors that result in bad FLUXUM/FLUXERRSUM.
      REAL TOL_FLUXERR_MEDIAN_RATIO
      PARAMETER ( TOL_FLUXERR_MEDIAN_RATIO = 50.0 )

      REAL*8  TOBS, LAMMIN, LAMMAX, SNR
      REAL*8  MJD, LAMMIN_BIN, LAMMAX_BIN
      REAL*8  FLUXSUM, SQERRSUM, FLAM, FLAMERR, DLAM
      REAL*8  FLAMERR_AVG, FLAMERR_RMS, FLAMERR_MEDIAN, RATIO
      INTEGER ispec, NLAMBIN, ilam, NBIN_REJECT
      INTEGER LEN_TOBS, LEN_SNR, LEN_LAMMIN, LEN_LAMMAX
      CHARACTER
     &    STR_TOBS*20, STR_SNR*20,
     &    STR_LAMMIN*20, STR_LAMMAX*20

      EXTERNAL ARRAYSTAT
C ----------- BEGIN --------


      DO 222 ispec = 1, NSPECTRUM

         CALL RDSPEC_DRIVER(ispec)  ! apr 5 2021

         MJD       = MJD_SPECTRUM(ispec)
         TOBS      = TOBS_SPECTRUM(ispec)
         NLAMBIN   = NLAMBIN_SPECTRUM(ispec)
         LAMMIN    = LAMMIN_SPECTRUM(1)
         LAMMAX    = LAMMAX_SPECTRUM(NLAMBIN)

         FLUXSUM = 0.0 ; SQERRSUM = 0.0

         CALL ARRAYSTAT(NLAMBIN, FLAMERR_SPECTRUM,
     &                  FLAMERR_AVG, FLAMERR_RMS, FLAMERR_MEDIAN)

         NBIN_REJECT = 0
         DO ilam = 1, NLAMBIN
             FLAM    = FLAM_SPECTRUM(ilam)
             FLAMERR = FLAMERR_SPECTRUM(ilam)
             LAMMIN_BIN = LAMMIN_SPECTRUM(ilam)
             LAMMAX_BIN = LAMMAX_SPECTRUM(ilam)

             RATIO = FLAMERR/FLAMERR_MEDIAN
             if ( RATIO > TOL_FLUXERR_MEDIAN_RATIO ) then
                NBIN_REJECT = NBIN_REJECT + 1
             else
               DLAM     = 2.0 ! LAMMAX_BIN - LAMMIN_BIN
               FLUXSUM  = FLUXSUM  + (FLAM*DLAM)
               SQERRSUM = SQERRSUM + (FLAMERR*DLAM)**2
             endif
         ENDDO
         SNR = FLUXSUM / sqrt(SQERRSUM)
         if ( NBIN_REJECT > 0 ) then
            write(6,212) SNLC_CCID(1:ISNLC_LENCCID),
     &                 NBIN_REJECT, NLAMBIN, MJD
 212        format(t5, 'WARNING(',A,'): flag ', I4,' of ', I5, 2x,
     &        'bins as FLAMERR outlier (MJD=',F9.3,')' )
         endif

         CALL dble2string_nospace(TOBS, STR_TOBS, LEN_TOBS)
         CALL dble2string_nospace(SNR,  STR_SNR,  LEN_SNR)
         CALL dble2string_nospace(LAMMIN,  STR_LAMMIN, LEN_LAMMIN)
         CALL dble2string_nospace(LAMMAX,  STR_LAMMAX, LEN_LAMMAX)

         WRITE(LUN,225)
     &      STR_TOBS(1:LEN_TOBS), STR_SNR(1:LEN_SNR),
     &      STR_LAMMIN(1:LEN_LAMMIN), STR_LAMMAX(1:LEN_LAMMAX)
 225     FORMAT('TAKE_SPECTRUM:  TOBS(', A, ')', 3x,
     &           'SNR(',A,')', 3x, 'SNR_LAMOBS(',A,':',A, ')' )

 222  CONTINUE

      RETURN
      END  ! WRITE_SIMLIB_SPECTRUM

C ================================================
CDECK  ID>,  DBLE2STRING_NOSPACE. 
      SUBROUTINE dble2string_nospace(VAL, STRING, LEN)
      IMPLICIT NONE
      REAL*8 VAL            ! (I) double value to convert
      CHARACTER STRING*(*)  ! (O) string with float value
      INTEGER  LEN          ! (O) length of string
      write(STRING,240) VAL
 240  format(F10.1)
      STRING = ADJUSTL(STRING)
      LEN = INDEX(STRING,' ') - 1
      RETURN
      END
CDECK  ID>,  FLOAT2STRING_NOSPACE. 
      SUBROUTINE float2string_nospace(VAL, STRING, LEN)
      IMPLICIT NONE
      REAL VAL              ! (I) float value to convert
      CHARACTER STRING*(*)  ! (O) string with float value
      INTEGER  LEN          ! (O) length of string

      write(STRING,240) VAL
 240  format(F10.1)

      STRING = ADJUSTL(STRING)
      LEN = INDEX(STRING,' ') - 1

      RETURN
      END
C =======================================================
CDECK  ID>,  FLUXERRCALC. 
      SUBROUTINE FLUXERRCALC(iepoch, FLUXCAL, FLUXCAL_ERR )
c
c Compute error from SKY,PSF and ZPT the same way as the
c simulation does.
c
c Fill
c   SNLC_SKYFLUXCAL(iepoch)           ! fluxcal per pixel
c   SNLC_FLUXCAL_ERRCALC(iepoch)      ! calculated flux error
c   SNLC_FLUXCAL_HOSTERRCALC(iepoch)  ! idem for host noise contribution
c where
c   SKYFLUX_ERR_PHOTO^2 = TOTAL_ERR^2 - SIGNAL_ERR^2
c
c and SKYFLUX_ERR_CALC is determined from the
c effective aperture.
c
c Feb 12,2012 - complete re-write.
c   The ZEROPT is now for the search run instead of for the
c   template run, so no need for obsolete KSUM to translate ZPT.
c   The 'template' noise is ingored since we assume that
c   many template images exist. To include template noise,
c   the SKY_SIG entry in the data file can be increased.
c   Another caveat is that FLUXERR is computed here in ADU,
c   but the reference FLUX can be in ADU or uJy.  To avoid
c   this confusion, the FLUXCAL error is computed from
c     FLUXCAL_ERRCALC = FLUXADU_ERRCALC * ADUSCALE / 10**[0.4*ZPT]
c   Thus comparing the calculated FLUXCAL_ERRCALC to the real
c   FLUXCAL_ERRTOT is always unamgiguous
c
c   The calibrated FLUXCAL and its error are passed as arguments
c   to allow using fitted quantities that may work better for
c   low SNR.
c
c
c Sep 21 2017:
c  + implement CHECK_SNANA_DUMP
c  + check PIXSIZE !!!
c  + allow calc for any format (previously skipped TERSE)
c
c Mar 2 2018:
c  + REAL -> REAL*8
c
c Nov 15 2019: load SNLC_FLUXCAL_ERRTEST = ERRCALC/ERRTRUE
c
c --------------------------------------------
      IMPLICIT NONE

      INTEGER iepoch                ! (I) epoch & SN indices
      REAL    FLUXCAL, FLUXCAL_ERR  ! (I) FLUXCAL and its error


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c local var

      REAL
     &   GAIN
     &  ,RDNOISE_pe, RDNOISE_ADU
     &  ,SQERR_TOT
     &  ,SQERR_SIGNAL
     &  ,SQERR_SKY      ! integrated over effective aperture
     &  ,SQERR_ZP
     &  ,SQSUM, TMPRAT, TMPERR
     &  ,SKY_SIG_ADU, SKY_SIG2_ADU ! search and template (ADU/pixel)
     &  ,SKY_SIGTOT_ADU
     &  ,SKY_AVG_ADU
     &  ,SBFLUXCAL, SBFLUXCAL_ERR, SBFLUXADU
     &  ,FLUXADU, FLUXADU_ERR
     &  ,ZP,  ZPERR, ZPSCALE, ZPDIF
     &  ,SQ1, SQRD,  SQERR_HOST, HOST_SKY_RATIO, ERRCALC, ERRTRUE
     &  ,SKYFLUX_ERR_PHOTO
     &  ,SKYFLUX_ERR_CALC
     &  ,PIXSIZE

      INTEGER IFILT_OBS, IFILT, DUMPFLAG, LENS
      CHARACTER cfilt*2, FNAM*12, STRING_INVALID*200

c function
      EXTERNAL NoiseEquivAperture, CHECK_SNANA_DUMP, ABORT_SNANA_DUMP
      REAL*8   NoiseEquivAperture
      INTEGER  CHECK_SNANA_DUMP_forC

      REAL*8  AREA, PSFSIG1, PSFSIG2, PSFRATIO, MJD8  ! args for above

C ------------- BEGIN --------------

      ERRCALC = -9.0
      SNLC_FLUXCAL_ERRCALC(iepoch)     = -9.0
      FNAM = 'FLUXERRCALC'

c initialize output

      SKYFLUX_ERR_PHOTO                = -9.0
      SKYFLUX_ERR_CALC                 = -9.0

c strip off observing conditions into local variables.

      ifilt_obs  = ISNLC_IFILT_OBS(iepoch)
      IFILT      = IFILTDEF_INVMAP_SURVEY(ifilt_obs)

      SKY_SIG_ADU   = SNLC_SKYSIG(iepoch)   ! search sky-sigma, ADU/pix
      SKY_SIG2_ADU  = max(0.0,SNLC_SKYSIG_T(iepoch))   ! idem for template
      PSFSIG1       = DBLE(SNLC_PSF_SIG1(iepoch))    ! Gauss sigma, pixel
      PSFSIG2       = DBLE(SNLC_PSF_SIG2(iepoch))    ! idem, 2nd component
      PSFRATIO      = DBLE(SNLC_PSF_RATIO(iepoch))
      GAIN          = SNLC_GAIN(iepoch)             ! e-/ADU
      RDNOISE_pe    = SNLC_RDNOISE(iepoch)          ! e-/pix
      ZP            = SNLC_ZEROPT(iepoch)
      ZPERR         = SNLC_ZEROPT_ERR(iepoch)
      SBFLUXCAL     = SNHOST_SBFLUXCAL(ifilt)
      SBFLUXCAL_ERR = SNHOST_SBFLUXCAL_ERR(ifilt)
      PIXSIZE       = SNLC_PIXSIZE
      ERRTRUE       = SNLC_FLUXCAL_ERRTOT(iepoch)

      SKY_SIGTOT_ADU = SQRT(SKY_SIG_ADU**2 + SKY_SIG2_ADU**2)

c check a few things.
      IF ( FLUXERRCALC_ZPTERR  .GE. 0.0 ) THEN
          ZPERR = FLUXERRCALC_ZPTERR
      ENDIF

      IF ( GAIN > 0.0 ) THEN
        RDNOISE_ADU  = RDNOISE_pe/GAIN     ! translate RDNOISE from e- to ADU
        SKY_AVG_ADU  = GAIN * (SKY_SIGTOT_ADU**2) ! needed to scale host noise
      ELSE
        SKY_AVG_ADU  = 0.0
        RDNOISE_ADU  = 0.0
      ENDIF

c ----------------------------------------------
c check for invalid/undefined values

      STRING_INVALID = ''
      if ( SKY_SIG_ADU   < 1.0E-4  ) then
         CALL APPEND_STRING(STRING_INVALID, 'SKY_SIG_ADU')
      endif
      if ( RDNOISE_ADU   < 0.0  ) then
         CALL APPEND_STRING(STRING_INVALID, 'RDNOISE')
      endif
      if ( PSFSIG1       < 0.001   ) then
         CALL APPEND_STRING(STRING_INVALID, 'PSFSIG1')
      endif
      if ( PSFSIG2       < 0.0     ) then
         CALL APPEND_STRING(STRING_INVALID, 'PSFSIG2')
      endif
      if ( PSFRATIO      < 0.0     ) then
         CALL APPEND_STRING(STRING_INVALID, 'PSFRATIO')
      endif
      if ( GAIN          < 0.01    ) then
         CALL APPEND_STRING(STRING_INVALID, 'GAIN')
      endif
      IF ( ZP < 0.01 .or. ZP > 60.0    ) then
         CALL APPEND_STRING(STRING_INVALID, 'ZP')
      endif
      IF ( ZPERR < 0.0 .or. ZPERR > 3.99     ) then
         CALL APPEND_STRING(STRING_INVALID, 'ZPERR')
      endif
      IF ( PIXSIZE       < 0.0001  ) then
         CALL APPEND_STRING(STRING_INVALID, 'PIXSIZE')
      endif

      IF ( STRING_INVALID .NE. '' ) GOTO 777  ! skip to dump

c set logical as soon as we get here.
      DO_FLUXERRCALC = .TRUE.

c use ZPT to convert calibated flux back into ADU
c (since FLUX in the data file can be either ADU or uJy)

      ZPDIF       = ZP - SNGL(ZEROPOINT_FLUXCAL_DEFAULT)
      ZPSCALE     = 10**(0.4*ZPDIF)   ! FLUXADU/FLUXCAL ratio
      FLUXADU     = ZPSCALE * FLUXCAL
      FLUXADU_ERR = ZPSCALE * FLUXCAL_ERR

c get signal error, but avoid problems with large negative fluxes
      tmprat = FLUXADU / FLUXADU_ERR
      if ( tmprat .GT. 0.5 ) then
         SQERR_SIGNAL = FLUXADU / GAIN   ! ADU^2
      else
         SQERR_SIGNAL = 0.0
      endif

c get effective area for sky-bkg = 1/[integral PSF^2], pixelsize^2
      AREA    = SNLC_PSF_NEA(iepoch) ! Mar 1 2021

c multiply skyerr^2 (per pixel) by effective area.
c Include optional read noise

      SQ1  = SKY_SIGTOT_ADU  * SKY_SIGTOT_ADU
      SQRD = RDNOISE_ADU  * RDNOISE_ADU
      SQERR_SKY = SNGL( AREA * ( SQ1 + SQRD ) )

c Include host noise if surface brightness (SB) is defined.

      SQERR_HOST = 0.0
      IF ( SBFLUXCAL > 0.001 .and. SKY_AVG_ADU > 0.0 ) THEN
         SBFLUXCAL  = SBFLUXCAL*(PIXSIZE**2)  ! -> FLUXCAL per pixel
         SBFLUXADU  = SBFLUXCAL * ZPSCALE
         SQERR_HOST = SNGL(AREA*SQ1*(SBFLUXADU/SKY_AVG_ADU)) ! scale sky noise^2
         SQERR_SKY  = SQERR_SKY + SQERR_HOST
      ENDIF
      HOST_SKY_RATIO = sqrt ( SQERR_HOST / ( SQERR_SKY-SQERR_HOST) )

      SKYFLUX_ERR_CALC = SQRT(SQERR_SKY)    ! ADU

c compute calibrated skyflux per pixel^2
c  (not for error calc, but to compare with host surface brightess)

      SNLC_SKYFLUXCAL(iepoch) =
     &   ((SKY_SIGTOT_ADU**2)*GAIN) / ZPSCALE

c compute error from zero-point smearing

      TMPERR    = 10**(0.4*ZPERR) - 1.0
      SQERR_ZP  = (FLUXADU * TMPERR)**2

c now combine calculated sky error and signal poisson noise
c for best estimate of flux error. This is what the simulation does.

      SQSUM = SQERR_SKY + SQERR_SIGNAL + SQERR_ZP
      ERRCALC                          = SQRT(SQSUM)/ZPSCALE
      SNLC_FLUXCAL_ERRCALC(iepoch)     = ERRCALC
      SNLC_FLUXCAL_HOSTERRCALC(iepoch) = SQRT(SQERR_HOST)/ZPSCALE

      IF ( ERRCALC > 0.0 .and. ERRTRUE > 0.0 ) THEN
        SNLC_FLUXCAL_ERRTEST(iepoch)  = ERRCALC/ERRTRUE
      ENDIF

c ------------------------------------
c Get photometry sky-error by subracting
c photo-stat signal error from total error

      SQERR_TOT    = FLUXADU_ERR * FLUXADU_ERR
      SQERR_SKY    = SQERR_TOT - SQERR_SIGNAL

      IF ( SQERR_SKY .GT. 0.0  ) THEN
         SKYFLUX_ERR_PHOTO = SQRT(SQERR_SKY)  ! ADU
      ELSE
         SKYFLUX_ERR_PHOTO = -9.0
      ENDIF

c --------------------------
c check for DUMP

777   CONTINUE
      IF ( DUMP_STRING .EQ. '' ) RETURN
      cfilt    = filtdef_string(ifilt_obs:ifilt_obs)
      MJD8     = SNLC8_MJD(iepoch)
      DUMPFLAG = CHECK_SNANA_DUMP_forC(FNAM,SNLC_CCID,CFILT,MJD8)

      if ( DUMPFLAG > 0 ) then

        print*,' '
        print*,' XXX ---------------------------------------------- '
        print*,' XXX FLUXERRCALC DUMP: '
        print*,' XXX CID=', SNLC_CCID(1:ISNLC_LENCCID),
     &         '  MJD=', sngl(MJD8), '  FILTER=',CFILT
        print*,' XXX FLUXADU = ', FLUXADU,' +- ', FLUXADU_ERR
        print*,' XXX FLUXCAL = ', FLUXCAL,' +- ', FLUXCAL_ERR
        print*,' XXX ZPT(AVG,ERR,SCALE) = ',
     &               ZP, ZPERR, ZPSCALE
        print*,' XXX PSFSIG1, PSFSIG2   = ',
     &               sngl(PSFSIG1), sngl(PSFSIG2),' Gauss pix'
        print*,' XXX GAIN               = ', GAIN
        print*,' XXX PIXSIZE, AREA      = ', PIXSIZE, sngl(AREA)
        print*,' XXX RDNOISE_ADU        = ', RDNOISE_ADU
        print*,' XXX SKY_SIG_ADU        = ', SKY_SIG_ADU,
     &             ' ADU/pix (search)'
        print*,' XXX SKY_SIG2_ADU       = ', SKY_SIG2_ADU,
     &             ' ADU/pix (template)'
        print*,' XXX SIG(HOST)/SIG(SKY) = ', HOST_SKY_RATIO
        print*,' XXX SKY_AVG_ADU        = ', SKY_AVG_ADU
        print*,' XXX SQERR_SIGNAL       = ', SQERR_SIGNAL,' ADU'
        print*,' XXX SQERR[SKY,TOT]     = ',
     &        SQERR_SKY, SQERR_TOT,' ADU '
        print*,' XXX SIM_MAGOBS         = ', SIM_EPMAGOBS(iepoch)
        print*,' XXX SIM_LIBID          = ', SIM_LIBID

        write(6,60) SKYFLUX_ERR_PHOTO, SKYFLUX_ERR_CALC
60      format(T2,' XXX SKYERR_ADU(PHOTO,CALC) =',F10.3,F10.3 )


        write(6,61) ERRTRUE, ERRCALC
61      format(T3,'XXX FLUXCAL_ERR(PHOTO,CALC)=',F10.3,F10.3 )
        print*,'   '

        IF ( STRING_INVALID .NE. '' ) THEN
          LENS = INDEX(STRING_INVALID,' ' ) - 1
          print*,' XXX Invalid quantities: ', STRING_INVALID(1:LENS)
        ENDIF

        if ( DUMPFLAG == 2 ) CALL ABORT_SNANA_DUMP()

      endif

      RETURN
      END

C =====================================
CDECK  ID>,  APPEND_STRING. 
      SUBROUTINE APPEND_STRING(STRING,APPEND)
c return STRING = STRING // ':' // APPEND
c Note that there are no blank spaces. Each item is separated by colon.
      IMPLICIT NONE
      CHARACTER STRING*(*), APPEND*(*)
      INTEGER LENS
C ----------- BEGIN ------------
      LENS = INDEX(STRING,' ' ) - 1
      IF ( LENS == 0 ) then
        STRING = APPEND
      ELSE
        STRING = STRING(1:LENS) // ':' // APPEND
      ENDIF

      RETURN
      END

C =====================================
CDECK  ID>,  CHECK_SNANA_DUMP_forC. 
      INTEGER FUNCTION CHECK_SNANA_DUMP_forC(FUN,CCID,BAND,MJD)

C add char(0) terminators to strings and then call
C C function CHECK_SNANA_DUMP(...)

      IMPLICIT NONE

c inputs
      CHARACTER FUN*(*), CCID*(*), BAND*(*)
      REAL*8  MJD

c local args
      INTEGER LEN_FUN, LEN_CCID, LEN_BAND, DUMPFLAG

c Declare C function
      EXTERNAL CHECK_SNANA_DUMP
      INTEGER CHECK_SNANA_DUMP
C ------------- BEGIN --------------

      LEN_FUN  = INDEX(FUN,  ' ' ) - 1
      LEN_CCID = INDEX(CCID, ' ' ) - 1
      LEN_BAND = INDEX(BAND, ' ' ) - 1

c      print*,' xxx FUN = ', FUN, LEN_FUN
c      print*,' xxx CCID = ', CCID, LEN_CCID
c      print*,' xxx BAND = ', BAND, LEN_BAND

      DUMPFLAG = CHECK_SNANA_DUMP(
     &        FUN(1:LEN_FUN) // char(0) ,
     &        CCID(1:LEN_CCID) // char(0) ,
     &        BAND(1:LEN_BAND) // char(0),
     &        MJD  )

      CHECK_SNANA_DUMP_forC = DUMPFLAG

      RETURN
      END

C ==========================================
CDECK  ID>,  AREAFRAC. 
      SUBROUTINE CCD_AREAFRAC(ep)

c Created aug 2014 by R.Kessler
c Use input globals NXPIX,NYPIX, XPIX(ep), YPIX(ep)
c to compute SNLC_AREAFRAC(ep) = A/AMAX where
c
c A    = area of largest rectangle containing XPIX, YPIX
c AMAX = area of CCD.
c
c For uniform CCD illumination, the distribution of AREAFRAC
c is uniform; AREAFRAC=0 at center of CCD, and AREAFRAC=1.00
c at edge.
c
c Also note that this works only for data because there is
c no pixel-coord input to the simulation ... but maybe
c someday XPIX and YPIX keys will be added to SIMLIB header.
c
c --------------
      IMPLICIT NONE

      INTEGER ep  ! (I) epoch index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      REAL XCEN, YCEN, YSCALE, X, Y, xy, A, AMAX

C ------------- BEGIN -------

      SNLC_AREAFRAC(ep) = -9.0 ;
      if ( SNLC_NXPIX .LE. 0.0 .or. SNLC_NYPIX .LE. 0.0 ) RETURN

c      print*,' xxx NXPIX,NYPIX = ', SNLC_NXPIX, SNLC_NYPIX

      XCEN   = SNLC_NXPIX/2.0
      YCEN   = SNLC_NYPIX/2.0
      YSCALE = SNLC_NYPIX/SNLC_NXPIX

      X  = ABS(SNLC_XPIX(ep) - XCEN)
      Y  = ABS(SNLC_YPIX(ep) - YCEN) / YSCALE  ! --> scale to square

      if ( X > Y ) THEN
         xy = X  ! half-len of square
      else
         xy = Y
      endif

      AMAX = SNLC_NXPIX**2  ! max possible area
      A    = 4. * xy * xy   ! area containing XPIX, YPIX/Yscale

      SNLC_AREAFRAC(ep) = A/AMAX

      RETURN
      END   ! end of CCD_AREAFRAC

C ==========================================
CDECK  ID>,  MON_SNANA. 
      SUBROUTINE MON_SNANA(IFLAG)

c Re-Created Feb 2013
c Driver for monitor tables.
c May 2 2020: add call to TABLE_MARZ

      IMPLICIT NONE

      INTEGER IFLAG   ! (I) see IFLAG_XXX params

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      LOGICAL   LTMP
      CHARACTER FNAM*10

C ------------ BEGIN ---------
      FNAM = 'MON_SNANA'

      IF( .NOT. USE_TABLEFILE ) RETURN

c ------------------------------------------------------
      IF ( MADE_LCPLOT )  N_SNLC_PLOT = N_SNLC_PLOT + 1
c ------------------------------------------------------

c fill OUTLIER table first so that SNANA table can include summary info
      IF ( OPT_TABLE(ITABLE_OUTLIER) > 0 ) THEN
         CALL TABLE_OUTLIER(IDTABLE_OUTLIER,IFLAG)
      ENDIF

      IF ( OPT_TABLE(ITABLE_SNANA) > 0 ) THEN
         CALL TABLE_SNANA(IDTABLE_SNANA,IFLAG)
      ENDIF

      LTMP = ( IFLAG .EQ. IFLAG_INI .or. MADE_LCPLOT )
      IF ( LTMP ) THEN
         CALL TABLE_CIDPTR(IFLAG)     ! init CID pointers for LC plots
      ENDIF

      IF ( MARZFILE_OUT .NE. '' ) THEN
         CALL TABLE_MARZ(IDTABLE_MARZ,IFLAG)
      ENDIF

      RETURN
      END     ! end of MON_SNANA

C ========================================
CDECK  ID>,  MON_HUBBLEREF. 
      SUBROUTINE MON_HUBBLEREF ( IERR )
c
c Plot theory MAG vs. Z for various Omega_{M,LAM,w}
c to have convenient theory references, and to
c crosscheck DLZ8 function.
c
c May 29, 2007: add 407 with Omega_MAT=1
c Feb 02, 2013: switch to SNHIST_XXX functions in sntools_output.c.
c Jul 08, 2016: plot curves from z=0-2 (instead of 0-1)
c Apr 23, 2019: add 8th plot with Orad = 1.2E-5
c Oct 23, 2020: use DLMAG_fortC to get DLMAG

      IMPLICIT NONE
      INTEGER IERR ! (O) 0=> OK


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



c local var

      INTEGER iz, NBZ(2), iplot, hid, LENTIT
      REAL*8  Z0, vPEC, Z0arg(2), zbinsize, ZLIM(2), DLMAG
      character chis*80

c define parameters for theory plots

      INTEGER NPL, NDIM
      PARAMETER (NPL = 8, NDIM=1 )

      REAL*8
     &   OM(NPL)  / 0.3, 0.3,  0.3,  0.3,  0.0,  0.0,  1.0,  0.3 /
     &  ,OL(NPL)  / 0.7, 0.7,  0.7,  0.0,  0.0,  1.0,  0.0,  0.7 /
     &  ,OR(NPL)  / 0.0, 0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  1.2E-5/
     &  ,w0(NPL)  /-1.0,-0.95,-0.95, 0.0,  0.0, -1.0, -1.0, -1.0 /
     &  ,wa(NPL)  / 0.0,-0.15, 0.15, 0.0,  0.0,  0.0,  0.0,  0.0 /

c     &  ,W(NPL)   /-1.0,-0.9, -0.84, 0.0,  0.0, -1.0, -1.0, -1.0 /
c     &  ,DWDZ(NPL)/ 0.0, 0.0,  0.65, 0.0,  0.0,  0.0,  0.0,  0.0 /

c functions

      REAL*8 DLMAG_FORTC

c ---------------- BEGIN ------------
      IERR = 0

      CALL PRBANNER ( "PLOT THEORY HUBBLE DIAGRAMS for REFERENCE")

c define Z bins for each plot

      ZLIM(1) = 0.0
      ZLIM(2) = 2.0
      NBZ(1)  = 200

      ZLIM(2) = 4.0
      NBZ(1)  = 200
ccccc

      Zbinsize = ( ZLIM(2)-ZLIM(1) ) / float(NBZ(1))

c book histos

      LENTIT = LEN(chis)

      DO iplot = 1, NPL
         write(chis,20) OM(iplot), OL(iplot),
     &                  OR(iplot)/1.0E-5, w0(iplot), wa(iplot)
20       format('MU vs. z (OM,OL,Or*E5 =', 3(F5.3,',') , ')',
     &            2x, 'w0,wa = ',2F6.2, ')'  )
         hid = 400 + iplot
         chis = chis(1:70) // char(0)
         CALL SNHIST_INIT(NDIM, hid, chis, NBZ, zlim(1), zlim(2),
     &                      LENTIT )
      END DO

c comput Mag vs. Z and fill histograms
      vPEC = 0.0

      DO 100 iz    = 1, NBZ(1)
        Z0 = zbinsize * ( float(iz)-0.5 )
      DO 200 iplot = 1, NPL

c use H0_DEFAULT instead of namelist H0_REF so that plot is always the same.

        DLMAG = DLMAG_fortC(z0,z0, vPEC, H0_DEFAULT,
     &    OM(iplot), OL(iplot), w0(iplot), wa(iplot) )

        HID = 400 + iplot
        Z0arg(1) = z0  ! use array to aboif gcc 10 warning
        CALL SNHIST_FILL( NDIM, HID, Z0arg, DLMAG )

200   CONTINUE
100   CONTINUE   ! iz


      RETURN
      END   ! end of MON_HUBBLEREF


C ===============================================
CDECK  ID>,  MJDSELECT. 
      LOGICAL FUNCTION MJDSELECT ( imjd, cutbit )
c
c Returns TRUE if this IMJD passes cuts
c CUTBIT = 0 => apply all cuts.
c
c If cutbit < 0, then all cuts are applied EXCEPT
c for |cutbit|; i.e., the cut on |cutbit| is ignored.
c This is useful to plot variables with cuts on all other
c variables except the one of interest. This allows you to
c see what gets cut.
c
c Note that if |cutbit| <= CUTBIT_MJD_MARKER,
c then this function really just selects from the
c SN-dependent cuts (like RA, redshfit, etc ...)
c and ignores the epoch index.
c
c Aug 22, 2007: modify to select NEWMJD instead of epoch.
c Nov 12, 2018: real MJD -> real*8 MJD
c -------------------------------------------
      IMPLICIT NONE

c declare subroutine args

      INTEGER
     &   imjd     ! (I) epoch index
     &  ,cutbit   ! (I) cut to ignore (if negative)


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c local var

      INTEGER EPMIN, acutbit   ! abs(cutbit)
      REAL*8    MJD
      INTEGER*8 CUTMASK8_ALL, CUTMASK8_TMP, OVP8

      LOGICAL LCUT_MJD, LCUT_SN

c -------------- BEGIN ------------------

      MJDSELECT =  .FALSE.

c -----------------------------------------------
c first make a few idiot checks

      EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,imjd)
      MJD   = SNGL(SNLC8_MJD(EPMIN))
      if ( MJD .LT. 40000. ) return

c ----------------------------------------

      IF ( CUTBIT .GE. 0 ) THEN
         MJDSELECT =  MJDMASK(imjd) .GT. 0
         RETURN
      ENDIF

c --------------------------------------------------
c Now we have a negative cutbit;
c check all cuts except |cutbit|

      acutbit = abs(cutbit)

      if ( acutbit .GT. NCUTBIT ) then
          write(c1err,60) cutbit
60        format('bad value of CUTBIT = ', I4 )
          CALL MADABORT("MJDSELECT", c1err, "")
      endif

c get cut-mask with all bits set.
c Note "SN" and EPOCHS have different cutmask.

      if ( acutbit .LE. CUTBIT_MJD_MARKER ) then
           CUTMASK8_ALL =  CUTMASK8_SN_ALL
           LCUT_SN    = .TRUE.
           LCUT_MJD   = .FALSE.
      else
           CUTMASK8_ALL =  CUTMASK8_MJD_ALL
           LCUT_SN      = .FALSE.
           LCUT_MJD     = .TRUE.
      endif

c define mask with all cuts except IBIT cut

      CUTMASK8_TMP = IBCLR ( CUTMASK8_ALL, acutbit-1 )

      IF ( LCUT_SN ) then
        OVP8  = IAND ( CUTMASK8_TMP, CUTMASK8_SN )
      ELSE
        OVP8  = IAND ( CUTMASK8_TMP, CUTMASK8_MJD(imjd))
      ENDIF

c  MJD passes if overlap mask equals mask with all
c  cuts EXCEPT |cutbit|

      MJDSELECT = ( OVP8 .EQ. CUTMASK8_TMP )

      RETURN
      END




C ==========================================
CDECK  ID>,  GET_TRESTVAR. 
      SUBROUTINE GET_TRESTVAR(
     &     NTLIST, TLIST, FLIST               ! (I)
     &   , CUTWIN_TREST                       ! (I)
     &   , CUTWIN_TRESTMIN, CUTWIN_TRESTMAX   ! (I)
     &   , CUTWIN_TREST2                      ! (I)
     &   , NFILT, TMIN, TMAX                  ! (O)
     &   , NFTMIN, NFTMAX, NFT2               ! (O)
     &   , TGAPMAX, T0GAPMAX )                ! (O)

c Created May 25, 2009 by R.Kessler
c Return rest-frame variables related to TREST,
c where TREST = 0 at peak.
c NOTES:
c   - assumes that TLIST is ordered from min to max.
c
c
c Aug 16, 2009: add more arguments: FLIST, NFTMIN, NFTMAX
c Aug 23, 2009: add NFILT output arg
c Oct 09, 2012: new args, CUTWIN_TREST2 and NFT2
c --------------------

      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



      INTEGER
     &   NTLIST        ! (I) size of TLIST array
     &  ,FLIST(NTLIST) ! (I) obs-filter list (to count NFTMIN[MAX])

      REAL
     &   TLIST(NTLIST)         ! (I) rest-frame list
     &  ,CUTWIN_TREST(2)       ! (I) global Trest-window
     &  ,CUTWIN_TRESTMIN(2)    ! (I) window to count NFTMIN
     &  ,CUTWIN_TRESTMAX(2)    ! (I) idem for NFTMAX
     &  ,CUTWIN_TREST2(2)      ! (I) generic window

      REAL
     &   TMIN, TMAX      ! (O) min, max Trest
     &  ,TGAPMAX         ! (O) max rest-frame gap (days)
     &  ,T0GAPMAX        ! (O) idem near peak

      INTEGER
     &   NFILT           ! (O) NFILT in FLIST array
     &  ,NFTMIN          ! (O) Nfilt passing CUTWIN_TRESTMIN
     &  ,NFTMAX          ! (O) Nfilt passing CUTWIN_TRESTMAX
     &  ,NFT2            ! (O) Nfilt passing CUTWIN_TREST2

c local car

      INTEGER
     &   i, ORDER, isort
     &  ,INDEX_SORT(MXEPOCH)
     &  ,IFILT_obs

      REAL
     &  Trest, Tlast, TGAP
     & ,T0GAPWIN(2)

      LOGICAL
     &   LT0GAP, LTMP
     &  ,LTMIN(MXFILT_ALL)
     &  ,LTMAX(MXFILT_ALL)
     &  ,LT2(MXFILT_ALL)
     &  ,LFILT(MXFILT_ALL)

c function

      EXTERNAL SORTFLOAT

C ------------------- BEGIN ---------------

c init output args
      Tmin      = +999.
      Tmax      = -999.
      TGAPMAX   = -999.
      T0GAPMAX  = -999.
      NFTMIN    = 0
      NFTMAX    = 0
      NFILT     = 0
      NFT2      = 0

c local stuff
      Tlast     =  999.

c construct T0GAP-window from other cuts
      T0GAPWIN(1)  = CUTWIN_TRESTMIN(2)
      T0GAPWIN(2)  = CUTWIN_TRESTMAX(1)

      DO IFILT_OBS = 1, MXFILT_ALL
        LFILT(IFILT_OBS) = .FALSE.
        LTMIN(IFILT_OBS) = .FALSE.
        LTMAX(IFILT_OBS) = .FALSE.
        LT2(IFILT_OBS)   = .FALSE.
      ENDDO


      ORDER = +1
      CALL sortFloat(NTLIST, TLIST, ORDER, INDEX_SORT )

      DO 444 i   = 1, NTLIST

         isort      = INDEX_SORT(i)
         Trest      = TLIST(isort)
         ifilt_obs  = FLIST(isort)

         if ( Trest .LT. CUTWIN_TREST(1)   ) GOTO 444
         if ( Trest .GT. CUTWIN_TREST(2)   ) GOTO 444

         IF ( .not. LFILT(ifilt_obs) ) then
            NFILT = NFILT + 1
            LFILT(ifilt_obs) = .TRUE.
         ENDIF

         LTMP = Trest .GE. CUTWIN_TRESTMIN(1) .and.
     &          Trest .LE. CUTWIN_TRESTMIN(2)
         IF ( LTMP .and.  .not. LTMIN(ifilt_obs) ) then
            NFTMIN = NFTMIN + 1
            LTMIN(ifilt_obs) = .TRUE.
         ENDIF

         LTMP = Trest .GE. CUTWIN_TRESTMAX(1) .and.
     &          Trest .LE. CUTWIN_TRESTMAX(2)
         IF ( LTMP .and.  .not. LTMAX(ifilt_obs) ) then
            NFTMAX = NFTMAX + 1
            LTMAX(ifilt_obs) = .TRUE.
         ENDIF

         LTMP = Trest .GE. CUTWIN_TREST2(1) .and.
     &          Trest .LE. CUTWIN_TREST2(2)
         IF ( LTMP .and.  .not. LT2(ifilt_obs) ) then
            NFT2 = NFT2 + 1
            LT2(ifilt_obs) = .TRUE.
         ENDIF

         Tmin = MIN ( Tmin, Trest )
         Tmax = MAX ( Tmax, Trest )

         if ( i .EQ. 1 ) then
           Tlast = Trest
           GOTO 444
         endif

         TGAP = Trest - Tlast
         if ( TGAP .GT. TGAPMAX ) then
             TGAPMAX = TGAP
         endif

         LT0GAP = .FALSE.
         if ( Trest > T0GAPWIN(1) .and. Trest < T0GAPWIN(2) )
     &       LT0GAP = .TRUE.
         if ( Tlast > T0GAPWIN(1) .and. Tlast < T0GAPWIN(2) )
     &       LT0GAP = .TRUE.
         if ( Trest > T0GAPWIN(2) .and. Tlast < T0GAPWIN(1) )
     &       LT0GAP = .TRUE.

         if ( LT0GAP .and. TGAP .GT. T0GAPMAX ) then
           T0GAPMAX = TGAP
         endif

         Tlast = Trest

444   CONTINUE

      RETURN
      END    ! GET_TRESTVAR




C ====================================================
CDECK  ID>,  DMP_CUTFAIL. 
      SUBROUTINE DMP_CUTFAIL ( IMJD, idebug )
c
c Created Jan 31, 2006 by R.Kessler
c
c Dump CUTBITS that fail for this 'IMJD'
c
c IDEBUG = 1 : general info for users
c IDEBUG = 2 : include detailed cut-masks for development
c
c Aug 2007: make special note when telescope is not found.
c Nov 2019: remove telescope logic and CUTBIT_IDTEL

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IMJD   ! (I) sparse SN index and epoch
      INTEGER idebug     ! (I) debug level

c local var

      INTEGER  cid, ibit, ii, EPMIN
      character ccid*(MXCHAR_CCID)
      LOGICAL LCUT, LTEST

C ------------------- BEGIN --------------

      cid  = SNLC_CID
      ccid = SNLC_CCID

      EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,IMJD)

c write MJD-cutmask in hex format

      IF ( IDEBUG .GT. 1 ) then
        write(6,20) CUTMASK8_MJD(IMJD), ccid, IMJD
20      format(T5, 'CUTMASK8_MJD = x', z16.16, 2x,
     &        'for  SN ', A12, 2x, 'NEWMJD ',I3 )
      ENDIF

c list failed bits for epoch-dependent cuts only

      DO ibit = CUTBIT_MJD_MARKER+1, NCUTBIT

        LTEST = BTEST ( CUTMASK8_MJD_ALL,        ibit-1 )
        LCUT  = BTEST ( CUTMASK8_MJD(IMJD),  ibit-1 )

        if ( LTEST .and.  .not. LCUT ) then
           ii = INDEX(cutvar_name(ibit),':') - 1

           write(6,30)
     &        IMJD, snlc8_MJD(EPMIN),
     &        ibit, cutvar_name(ibit)(1:ii)

30         format(T5,'NEWMJD ',I2,1x,'(MJD=',F9.3,')',2x,
     &         'Failed CUTBIT ', I3, ' : ', A  )

        endif

      ENDDO

      RETURN
      END  ! end DMP_CUTFAIL

C =============================================
CDECK  ID>,  DMP_SNFAIL. 
      SUBROUTINE DMP_SNFAIL()
c
c Dump utility for SN that fails cuts
c Shows cuts that fail for SN, and cuts that fail for each epoch.
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER imjd, ibit, ii
      LOGICAL LCUT, LTEST

C ---------------- BEGIN ------------

      print*,' '
      print*,' ========== DMP_SNFAIL for CID ', SNLC_CID,
     &        ' ================= '

      DO 100 ibit = 1, CUTBIT_MJD_MARKER

        LTEST = BTEST ( CUTMASK8_SN_ALL,  ibit-1 )
        LCUT  = BTEST ( CUTMASK8_SN,      ibit-1 )

        if ( LTEST .and.  .not. LCUT ) then
           ii = INDEX(cutvar_name(ibit),':') - 1

           write(6,30) ibit, cutvar_name(ibit)(1:ii)
     &          ,SNLC_CUTVAR(ibit)
     &          ,CUTWIN_VAR(1,ibit)
     &          ,CUTWIN_VAR(2,ibit)
30         format(T5, 'Failed SN cut ',I2,' : ', A,
     &        ' =', F8.2, ' (cutwin=',F8.1,' to ',G10.3,  ')'  )
        endif

100   CONTINUE

      do imjd = 1, ISNLC_NEWMJD_STORE
         CALL DMP_CUTFAIL ( IMJD, 1 )  ! MJD cut-failures
      enddo

      print*,' ===================================== '
      print*,' '
      RETURN
      END


C ==================================================
CDECK  ID>,  SET_CUTMASK. 
      SUBROUTINE SET_CUTMASK()

c
c Created Jan 31, 2006 by R.Kessler
c
c After SN data are read in, this routine
c sets CUTMASK8_SN and CUTMASK8_MJD(epoch),
c and then determines which SN and epochs pass/fail cuts.
c
c To test SN
c   if ( CUTMASK8_SN .EQ. CUTMASK8_SN_ALL ) then
c      use this SN
c   endif
c
c To test epochs,
c
c    if (  btest(EPOCHMASK(isn),epoch-1 )  ) then
c       use this epoch
c    endif
c
c       HISTORY
c    ~~~~~~~~~~~~~
c Feb 7, 2014 ZZ->1 if SNLC_REDHIFT < 0 ; fixes TOBSMIN/TOBSMAX.
c
c Jan 11 2015: call REJECT_PRESCALE to set LCUT for CUTBIT_PRESCALE
c
c Jan  8 2017: abort if ISNLC_TYPE > MXTYPE
c Jul 11 2017: declare PS8 as REAL*8, not INT*8
c Dec 09 2017: remove REJECT_PRESCALE() and move it to SNANA_DRIVER
c Dec 18 2017: set cut for PSF
c Feb 27 2018: set cut for ZP in Npe; see CUTWIN_ZP
c Feb 06 2020: add cut for Trest_trueflux
c Feb 20 2020: make sure PHOTPROB cut passes if PHOTPROB < 0
c Mar 16 2021: load SIM_EPPULL to enable cut on PULL
c -----------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


c local var

      INTEGER
     &   NEWMJD, imjd, NEWMJD_CUTS
     &  ,EPMIN, EPMAX, ep, ifilt, ifilt_obs
     &  ,ICUT, i, cid,  NTLIST
     &  ,FLIST(MXEPOCH)
     &  ,NFILT, NFTMIN, NFTMAX, NFT2

      INTEGER*8  CUTMASK8_TMP, OVP8_SN, OVP8_ALL

      LOGICAL LTEST, LCUT, LCUT1, LCUT2

      REAL  TMP, Tmin, Tmax, ZZ, TGAPMAX, T0GAPMAX, TLIST(MXEPOCH)
      REAL  TREST, TRUEMAG, PHOTPROB

c functions
      LOGICAL MJDSELECT, LCIDSELECT

c ---------------- BEGIN ---------------

      NEWMJD       = ISNLC_NEWMJD_STORE
      NEWMJD_CUTS  = 0

c init common block var output

      CUTMASK8_SN   = 0


      Do imjd = 1, NEWMJD
         CUTMASK8_MJD(imjd) = 0
         MJDMASK(imjd)      = 0  ! init
      End Do

      CID = SNLC_CID

      IF ( SNLC_REDSHIFT > 0. ) THEN
         zz  = 1.0 + SNLC_REDSHIFT
      ELSE
         zz = 1.0  ! avoid crazy Tobsmin/max
      ENDIF

c check privat-var cuts and user cuts from private code
      IF ( .not. PASS_PRIVCUTS ) ISNLC_CUTFLAG_PRIVATE = 0
      IF ( .not. PASS_SIMCUTS  ) ISNLC_CUTFLAG_SIMVAR  = 0

c --------------------------------------------------------
c first evaluate SNLC_CUTVAR array for MJD-dependent
c SNLC_XXX arrays.

      DO 100 imjd = 1, NEWMJD

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,imjd)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,imjd)

c Dec 18 2017: replace cloudAVG with PSF cut. Note that cut is in ARCSEC
         SNEP_CUTVAR(CUTBIT_PSF,imjd)  =
     &       SNLC_PSF_SIG1(EPMIN) * (SNLC_PIXSIZE * 2.355)

         SNEP_CUTVAR(CUTBIT_ZP,imjd) =
     &       SNLC_ZEROPT_forCUT(EPMIN)

         SNEP_CUTVAR(CUTBIT_ZPERR,imjd) =
     &       SNLC_ZEROPT_ERR(EPMIN)      ! Feb 2020

         PHOTPROB = SNLC_PHOTPROB(EPMIN)
         IF ( PHOTPROB < 0.0 ) PHOTPROB = 1.0  ! undefined PHOTPROB passes cut
         SNEP_CUTVAR(CUTBIT_PHOTPROB,imjd)  = PHOTPROB

         SNEP_CUTVAR(CUTBIT_ERRTEST,imjd)  =
     &       SNLC_FLUXCAL_ERRTEST(EPMIN)

         SNEP_CUTVAR(CUTBIT_SIMPULL,imjd)  =
     &       SIM_EPPULL(EPMIN)

         SNEP_CUTVAR(CUTBIT_TREST,imjd)  =
     &       SNLC_TREST(EPMIN)

         SNEP_CUTVAR(CUTBIT_TOBS,imjd)  =
     &       SNLC_TOBS(EPMIN)

         SNEP_CUTVAR(CUTBIT_MJD,imjd)  =
     &       SNGL( SNLC8_MJD(EPMIN) )

c Requiring valid true flux is a little tricky.
c Motivation is for fake light curves on images where a few epochs
c didn't get overlaid for unknown reasons.
         SNEP_CUTVAR(CUTBIT_TREST_TRUEFLUX2,imjd) = 1.0
         IF ( ISJOB_SIM ) THEN
            Trest   = SNLC_TREST(EPMIN)
            TRUEMAG = SIM_EPMAGOBS(EPMIN)
            LCUT1   = (TREST > CUTWIN_TREST_TRUEFLUX(1) .and.
     &                 TREST < CUTWIN_TREST_TRUEFLUX(2) )
            LCUT2   = (TRUEMAG < 40)
            if ( LCUT1 .and. (.not. LCUT2) ) then
              SNEP_CUTVAR(CUTBIT_TREST_TRUEFLUX2,imjd) = 0.0
            endif
         ENDIF

100   CONTINUE

c ----------------------------------------------------
c Evaluate cutmask for each epoch

      DO 200 imjd = 1, NEWMJD

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,imjd)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,imjd)

        CUTMASK8_TMP = 0
        CUTMASK8_MJD(imjd) = CUTMASK8_TMP

      DO 201 icut  = CUTBIT_MJD_MARKER+1, NCUTBIT

          LTEST = BTEST ( CUTMASK8_MJD_ALL, icut-1 )
          if ( .NOT. LTEST ) goto 201

          tmp = snep_cutvar(icut,imjd)
          LCUT = tmp .GE. cutwin_var(1,icut) .and.
     &           tmp .LE. cutwin_var(2,icut)

c set cut-bit if cut is satisfied
          if ( LCUT ) then
             CUTMASK8_TMP = IBSET ( CUTMASK8_TMP, icut-1 )
          endif


201   CONTINUE   ! end ICUT loop

c if all cuts are satisfied for this epoch, then set MJDMASK

        CUTMASK8_MJD(imjd) = CUTMASK8_TMP


        if ( CUTMASK8_TMP .EQ. CUTMASK8_MJD_ALL ) then
           MJDMASK(imjd) = 1
           NEWMJD_CUTS   = NEWMJD_CUTS + 1
        endif

200   CONTINUE  ! end of IMJD loop

c -----------------------------------------------
c store number of epochs passing cuts,

      ISNLC_NEWMJD_CUTS = NEWMJD_CUTS

c -------------------------------------------
c fill SNLC_CUTVAR array for SN-dependent variables
c Note that this is done AFTER epoch-dependent cutmask
c so that NEWMJD_CUTS can be evaluated correctly.

         imjd  = 1

         SNLC_CUTVAR(CUTBIT_CID)       =
     &        float ( SNLC_CID )

         SNLC_CUTVAR(CUTBIT_SNTYPE)     =
     &        float ( ISNLC_TYPE )

         SNLC_CUTVAR(CUTBIT_REDSHIFT)  =
     &       SNLC_REDSHIFT

         SNLC_CUTVAR(CUTBIT_REDSHIFT_ERR)  =
     &       SNLC_REDSHIFT_ERR

         SNLC_CUTVAR(CUTBIT_RA)  =
     &       SNGL( SNLC8_RA )
         SNLC_CUTVAR(CUTBIT_DEC)  =
     &       SNGL( SNLC8_DEC )

         SNLC_CUTVAR(CUTBIT_HOSTSEP)  = SNHOST_ANGSEP(1)

         SNLC_CUTVAR(CUTBIT_PEAKMJD)  =
     &       SNLC_SEARCH_PEAKMJD

         SNLC_CUTVAR(CUTBIT_NMJD_INCLUDE)  =
     &       float ( ISNLC_NMJD_INCLUDE )

         SNLC_CUTVAR(CUTBIT_SNRMAX)  =
     &       SNLC_SNRMAX_FILT(0)
         SNLC_CUTVAR(CUTBIT_SNRMAX2)  =
     &       SNLC_SNRMAX_FILT(0)

         SNLC_CUTVAR(CUTBIT_NEPOCH)  =
     &       float ( ISNLC_NEPOCH_STORE )

         SNLC_CUTVAR(CUTBIT_SEARCH)  =
     &       SIM_SEARCHEFF_MASK

         SNLC_CUTVAR(CUTBIT_NFIELD)  =
     &       float ( ISNLC_NFIELD_OVP )

         SNLC_CUTVAR(CUTBIT_MWEBV)  =
     &        SNLC_MWEBV               ! added May 2012

         SNLC_CUTVAR(CUTBIT_NSEASON_ACTIVE)  =
     &        float(NSEASON_ACTIVE)

         SNLC_CUTVAR(CUTBIT_REQEP)  =
     &        float( ISNLC_CUTFLAG_REQEP )   ! added Sep 17 2017

         SNLC_CUTVAR(CUTBIT_PRIVATE)  =
     &        float( ISNLC_CUTFLAG_PRIVATE )   ! added Nov 3 2014

         SNLC_CUTVAR(CUTBIT_SIMVAR)  =
     &        float( ISNLC_CUTFLAG_SIMVAR )    ! added Dec 2018

c ---------------------------------------
c set TREST-related variables.
c Warning: this code must go here after evaluating
c cutmask from all other cuts.

c first build TLIST array for epochs that pass MJDSELECT()
       NTLIST = 0
       DO 444 imjd = 1, NEWMJD
         if ( .NOT. MJDSELECT(imjd,0)  ) GOTO 444
         EPMIN     = ISNLC_EPOCH_RANGE_NEWMJD(1,imjd)
         EPMAX     = ISNLC_EPOCH_RANGE_NEWMJD(2,imjd)
         DO EP     = EPMIN, EPMAX
           NTLIST  = NTLIST + 1
           TLIST(NTLIST) = SNLC_Trest(EP)
           FLIST(NTLIST) = ISNLC_IFILT_OBS(EP)
         ENDDO
444    CONTINUE

       CALL GET_TRESTVAR(NTLIST, TLIST, FLIST     ! (I)
     &       ,CUTWIN_TREST                        ! (I)
     &       ,CUTWIN_TRESTMIN, CUTWIN_TRESTMAX    ! (I)
     &       ,CUTWIN_TREST2                       ! (I)
     &       ,NFILT, TMIN, TMAX                   ! (O)
     &       ,NFTMIN, NFTMAX, NFT2                ! (O)
     &       ,TGAPMAX, T0GAPMAX )                 ! (O)

       SNLC_TGAPMAX  = TGAPMAX
       SNLC_T0GAPMAX = T0GAPMAX

       SNLC_Trestmin = Tmin
       SNLC_Trestmax = Tmax
       SNLC_TrestRange = Tmax - Tmin    ! Dec 2017

       SNLC_Tobsmin = Tmin * ZZ
       SNLC_Tobsmax = Tmax * ZZ

       ISNLC_NFILT_TRESTMIN  = NFTMIN
       ISNLC_NFILT_TRESTMAX  = NFTMAX
       ISNLC_NFILT_TREST2    = NFT2

c ----------------------------------------------------

       imjd  = 1
       EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,imjd)

       SNLC_CUTVAR(CUTBIT_TRESTMIN)  =
     &       SNLC_TRESTMIN
       SNLC_CUTVAR(CUTBIT_TRESTMAX)  =
     &       SNLC_TRESTMAX
       SNLC_CUTVAR(CUTBIT_TRESTRANGE)  =
     &       SNLC_TRESTRANGE

       SNLC_CUTVAR(CUTBIT_TobsMIN)  =
     &       SNLC_TobsMIN
       SNLC_CUTVAR(CUTBIT_TobsMax)  =
     &       SNLC_TobsMax

       SNLC_CUTVAR(CUTBIT_TGAPMAX)  =
     &       SNLC_TGAPMAX
       SNLC_CUTVAR(CUTBIT_T0GAPMAX)  =
     &       SNLC_T0GAPMAX

       SNLC_CUTVAR(CUTBIT_NFILT_SNRMAX)  =
     &       float ( ISNLC_NFILT_SNRMAX )

       SNLC_CUTVAR(CUTBIT_NFILT_SNRMAX2)  =
     &       float ( ISNLC_NFILT_SNRMAX2 )

       SNLC_CUTVAR(CUTBIT_NFILT_TRESTMIN)  =
     &       float ( ISNLC_NFILT_TRESTMIN )

       SNLC_CUTVAR(CUTBIT_NFILT_TRESTMAX)  =
     &       float ( ISNLC_NFILT_TRESTMAX )

       SNLC_CUTVAR(CUTBIT_NFILT_TREST2)  =
     &       float ( ISNLC_NFILT_TREST2 )

c always make sure TREST2 cut passes since the only cut of
c interest in in NFILT_TREST2.
       SNLC_CUTVAR(CUTBIT_TREST2)  = CUTWIN_TREST2(1) + 0.1


c be careful with the SNRMAX indices.
       DO i         = 1, NFILT_SNRMAX  ! sparse index for SNRMAX cut
          ifilt_obs = IFILT_SNRMAX(i)  ! absolute filtetr index
          ifilt     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)   ! sparse filt index
          icut      = CUTBIT_OFFSET_SNRMAX + i
          SNLC_CUTVAR(icut) = SNLC_SNRMAX_FILT(ifilt)
       ENDDO

c be careful with the HOST_SBFLUX indices.
       DO i         = 1, NFILT_HOST_SBFLUX  ! sparse index for SNRMAX cut
          ifilt_obs = IFILT_HOST_SBFLUX(i)  ! absolute filtetr index
          ifilt     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)   ! sparse filt index
          icut      = CUTBIT_OFFSET_SBFLUX + i
          SNLC_CUTVAR(icut) =
     &         SNHOST_SBFLUXCAL(ifilt)
       ENDDO

c -----------------------------------------------------
c After epochs, evaluate SN cut-mask
c  (epoch-independent => use 1st epoch of SNLC_CUTVAR)
c This part comes AFTER epochmask so that we can cut
c on NEWMJD_CUTS

         CUTMASK8_TMP = 0

      DO 300 icut  = 1, CUTBIT_MJD_MARKER

          LTEST = BTEST (CUTMASK8_SN_ALL , icut-1 )
          if ( .NOT. LTEST ) GOTO 300

          tmp = snlc_cutvar(icut)
          LCUT = tmp .GE. cutwin_var(1,icut) .and.
     &           tmp .LE. cutwin_var(2,icut)

c special check for CID cut. This cut is probably redundant
c with the cut in PARSE_CID.

          if ( icut .EQ. CUTBIT_CID ) then
            LCUT = LCIDSELECT(SNLC_CID,SNLC_CCID,SNLC_IAUC)
          endif

c set cut-bit if cut is satisfied

          if ( LCUT ) then
             CUTMASK8_TMP = IBSET ( CUTMASK8_TMP, icut-1 )
             NACCEPT_CUT(icut) = NACCEPT_CUT(icut) + 1
          endif

300   CONTINUE   ! end ICUT loop

      CUTMASK8_SN = CUTMASK8_TMP

c set SN cut-logical

      IF ( CUTMASK8_SN .EQ. CUTMASK8_SN_ALL  ) THEN
         LSNCUTS       = .TRUE.
         CUTFLAG_SNANA = IBSET(CUTFLAG_SNANA,0)
         N_SNLC_CUTS   = N_SNLC_CUTS + 1
         if (NSPECTRUM > 0) N_SNLC_SPEC = N_SNLC_SPEC + 1
         if(SNHOST_ZSPEC(1) > 0.) N_SNHOST_ZSPEC = N_SNHOST_ZSPEC+1
         if(SNHOST_ZPHOT(1) > 0.) N_SNHOST_ZPHOT = N_SNHOST_ZPHOT+1
      ENDIF

c Jan 3, 2013
c increment Number of SN passing each incremental cut,
c and versus type. This info is dumped at the end of the
c job to trace where SN are lost.

      IF ( ISNLC_TYPE < 0 ) RETURN

      IF ( ISNLC_TYPE > MXTYPE ) THEN
        write(C1err,661) ISNLC_TYPE, MXTYPE
661     format('TYPE=',I5,' exceeds bound: MXTYPE=',I4 )
        C2err = 'Check CID = ' // SNLC_CCID
        CALL MADABORT("SET_CUTMASK", c1err, c2err )
      ENDIF

      CUTMASK8_TMP = 0
      DO icut = 1, NCUTBIT_SNLC
         CUTMASK8_TMP = IBSET(CUTMASK8_TMP,icut-1)
         OVP8_ALL     = IAND(CUTMASK8_TMP,CUTMASK8_SN_ALL)
         OVP8_SN      = IAND(CUTMASK8_SN,OVP8_ALL)
         IF ( OVP8_SN .EQ. OVP8_ALL ) THEN
            NPASSCUT_INCREMENT(ISNLC_TYPE,ICUT) =
     &      NPASSCUT_INCREMENT(ISNLC_TYPE,ICUT) + 1

c increment all types with ITYPE=-1 (Aug 2013)
            NPASSCUT_INCREMENT(-1,ICUT) =
     &      NPASSCUT_INCREMENT(-1,ICUT) + 1
         ENDIF
      ENDDO

      RETURN
      END  ! end of SET_CUTMASK


C ==============================================
CDECK  ID>,  LCIDSELECT. 
      LOGICAL FUNCTION LCIDSELECT(CID,CCID,IAUC)
c
c Created Dec 4, 2012 by R.Kessler
c Returns TRUE if current CID/CCID is accepted by
c any of
c  CUTWIN_CID     (integer window of CID to accept)
c  SNCID_LIST     (integer list of CID to accept)
c  SNCCID_LIST    (char list of CCID to accept)
c
c and is NOT rejected by
c  SNCID_IGNORE       (integer list of CID to ignore)
c  SNCCID_IGNORE_ALL  (char list of CCID to ignore)
c
c This function replaces much of the obsolete CIDMASK(CID) array
c to avoid declaring such a large array.
c
c
c Oct 10 2020: fix bug checking SNCCID_IGNORE_ALL
c Jan 04 2021: check OPT_SNCID_LIST for option to use alternate PKMJDINI
C ---------------------------

      IMPLICIT NONE

c input function args
      INTEGER CID
      CHARACTER CCID*(*), IAUC*(*)


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


      INTEGER i, LEN, LENCCID, LENIAUC, ISN_MATCH
      REAL XCID
      CHARACTER CCIDTMP*(MXCHAR_CCID)

c functions
      LOGICAL   STRINGMATCH
      INTEGER   MATCH_CIDLIST_EXEC
      EXTERNAL  MATCH_CIDLIST_EXEC
c ------------------ BEGIN ---------------

      LCIDSELECT = .FALSE.
      LENCCID = INDEX(CCID//' ' , ' ') - 1
      INDEX_CID_MATCH = -9
c ----------------------------
c first check IGNORE Lists

      i = 1
      DO 30 WHILE ( SNCID_IGNORE(i) .GE. 1 )
        if ( CID .EQ. SNCID_IGNORE(i) ) GOTO 800
        i = i + 1
30    CONTINUE

      DO 40 i = 1, NCCID_IGNORE
        LEN   = INDEX(SNCCID_IGNORE_ALL(i),' ') - 1
        IF ( LEN .NE. LENCCID ) GOTO 40
        if ( CCID(1:LEN) .EQ. SNCCID_IGNORE_ALL(i)(1:LEN)) GOTO 800
40    CONTINUE

c -----------------------------
c Check integer window

      XCID = FLOAT(CID)
      IF ( XCID .GE. CUTWIN_CID(1) .and.
     &     XCID .LE. CUTWIN_CID(2) ) then
        LCIDSELECT = .TRUE.
        GOTO 800
      ENDIF

c Since  integer list is small, use brute-force looping.
      i = 1
      DO 130 WHILE ( SNCID_LIST(i) .GE. 1 )
         if ( CID .EQ. SNCID_LIST(i) ) then
            LCIDSELECT = .TRUE.
            GOTO 800
         endif
         i = i + 1
130   CONTINUE

c use hash table to check list of CID strings since this list
c can be quite large.
      CCIDTMP = CCID(1:LENCCID) // char(0)
      ISN_MATCH = MATCH_CIDLIST_EXEC(CCIDTMP,LENCCID)
      if ( ISN_MATCH  < 0 ) then   ! try IAUC name
         LENIAUC = INDEX(IAUC,' ') - 1
         CCIDTMP = IAUC(1:LENIAUC) // char(0)
         ISN_MATCH  = MATCH_CIDLIST_EXEC(CCIDTMP,LENIAUC) ! use hash table
         if ( ISN_MATCH .GE. 0 ) CCID = IAUC ! write IAUC to output table
      endif
      INDEX_CID_MATCH = ISN_MATCH     ! load global
      LCIDSELECT = (ISN_MATCH .GE. 0)
      if ( LCIDSELECT ) GOTO 800

c - - - - -
c finally, check list of CIDs on the MJD-interpolation list;
c see &SNLCINP namelist input SNMJD_LIST_FILE

      DO 240 i = 1, N_INTERP_MJDLIST
        CCIDTMP = INTERP_CCIDLIST(i)
        IF ( STRINGMATCH(CCIDTMP,CCID) ) THEN
           LCIDSELECT = .TRUE.
           GOTO 800
        ENDIF

c Dec 2015: also check match with IAUC name
        IF ( STRINGMATCH(CCIDTMP,IAUC) ) THEN
           CCID       = IAUC  ! so that IAUC is written to output
           LCIDSELECT = .TRUE.
           GOTO 800
        ENDIF

240   CONTINUE

800   CONTINUE

      RETURN
      END   ! end LCIDSELECT


C ====================================
CDECK  ID>,  STRINGMATCH. 
      LOGICAL FUNCTION STRINGMATCH(STR1,STR2)

C Created Dec 2015
C Return True of STR1=STR2

      IMPLICIT NONE
      CHARACTER STR1*(*), STR2*(*)
      INTEGER   LEN1, LEN2

C ------------------ BEGIN -------------

      STRINGMATCH = .FALSE.
      LEN1 = INDEX(STR1,' ') -1
      LEN2 = INDEX(STR2,' ') -1
      IF ( LEN1 .NE. LEN2 ) RETURN

      IF ( STR1(1:LEN1) .EQ. STR2(1:LEN2) ) THEN
        STRINGMATCH = .TRUE.
      ENDIF

      RETURN
      END

C ======================
CDECK  ID>,  STEPFUN8. 
      DOUBLE PRECISION FUNCTION SMOOTH_STEPFUN8(SEP,SEPMAX)
c
c Created Sep 8, 2009 by R.Kessler
c
c Define smooth function that goes from 0 to 1 between
c -SEPMAX and SEPMAX, and returns 0.5 at SEP=0.
c Return value of function at SEP.
c Function is atan.
c --------------------------

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


      REAL*8 SEP, SEPMAX  ! (I)
      REAL*8 TAU, F
c ----------- BEGIN ----------

      IF ( SEP .GT. SEPMAX ) THEN
         SMOOTH_STEPFUN8 = 1.0
         RETURN
      ENDIF
      IF ( SEP .LT. -SEPMAX ) THEN
         SMOOTH_STEPFUN8 = 0.0
         RETURN
      ENDIF

      TAU  = .1 * SEPMAX
      F    = 0.5 * (1. + ATAN(SEP/TAU)/ATAN(SEPMAX/TAU) )
      SMOOTH_STEPFUN8 = F

      RETURN
      END


C =======================================
CDECK  ID>,  GET_HOSTXTINCT8. 
      DOUBLE PRECISION FUNCTION GET_HOSTXTINCT8 ( AV, RV, Lambda )
      IMPLICIT NONE

c input args

      REAL*8
     &   AV      ! (I) extinction at  5495 A
     &  ,RV      ! (I) assumed A(V)/E(B-V) (e.g., = 3.1 in the LMC)
     &  ,Lambda  ! (I) wavelen, A

c local var

      REAL*8 x, y, a, b, fa, fb, dx, dx2, dx3
      REAL*8 y2, y3, y4, y5, y6, y7

C --------------- BEGIN --------------

      x = 10000./lambda    ! inverse wavelength in microns
      y = x - 1.82;

      if (x .GE. 0.3 .and. x .LT. 1.1) then   !  IR

         a =  0.574*(x**1.61)
         b = -0.527*(x**1.61)

      else if (x .GE. 1.1 .and. x .LT. 3.3) then    ! Optical/NIR

         y2 = y**2
         y3 = y**3
         y4 = y**4
         y5 = y**5
         y6 = y**6
         y7 = y**7

         a = 1. + 0.17699*y  - 0.50447*y2 - 0.02427*y3
     &          + 0.72085*y4 + 0.01979*y5 - 0.77530*y6
     &          + 0.32999*y7

         b = 1.41338*y + 2.28305*y2 + 1.07233*y3 - 5.38434*y4
     &                 - 0.62251*y5 + 5.30260*y6 - 2.09002*y7

      else if ( x .GE. 3.3 .and. x .LT. 8.0) then    ! UV

         if (x .GT. 5.9) then
          dx  = x - 5.9
          dx2 = dx  * dx
          dx3 = dx2 * dx
          fa = -0.04473*dx2 - 0.009779*dx3
          fb =  0.21300*dx2 + 0.120700*dx3
        else
          fa = 0.0
          fb = 0.0
        endif

        a =  1.752 - 0.316*x - 0.104/((x-4.67)**2 + 0.341) + fa
        b = -3.090 + 1.825*x + 1.206/((x-4.62)**2 + 0.263) + fb

      else if (x .GE. 8.0 .and.  x .LE. 10.0 ) then  ! Far-UV

         dx  = x - 8.0
         dx2 = dx * dx
         dx3 = dx2 * dx

         a = -1.073 - 0.628*dx + 0.137*dx2 - 0.070*dx3
         b = 13.670 + 4.257*dx - 0.420*dx2 + 0.374*dx3

      else
          a = 0.0
          b = 0.0
      ENDIF

      GET_HOSTXTINCT8 = av*(a + b/RV)

      RETURN
      END

C ====================================================
CDECK  ID>,  DFINT. 
C
C Revision 1.1.1.1  1996/02/15 17:48:36  mclareni
C Kernlib
C
C
C#include "kernnum/pilot.h"

          DOUBLE PRECISION FUNCTION DFINT(NARG,ARG,NENT,ENT,TABLE)
C
          IMPLICIT NONE
C
C   INTERPOLATION ROUTINE. AUTHOR C. LETERTRE.
C   MODIFIED BY B. SCHORR, 1.07.1982.
C
C   Modified from CERNLIB funtion FINT to double precision
C by David Cinabro Feb 2006.  I did not make stylistic changes,
C even though those would seem to be called for.
C
c Oct 30, 2006 RSK : change arg dimensions from 9 to 90
c
c May 08, 2012: RSK replace hard-wired '90' with NARG in arg declarations
c Jul 10, 2012: RSK replace NARG with 500 (fix bug when NARG=1)
c
c Oct 26 2015: replace XXX(500) with  XXX(NARG) to avoid compile warnings.
c Jan 07 2016: ENT(NARG) -> ENT(500)
c Jan 11 2019: use NARG as argument instead of 500

          INTEGER   NARG
          INTEGER   NENT(NARG+100)
ccc          REAL*8    ARG(NARG), ENT(500), TABLE(500)
          REAL*8    ARG(NARG+100), ENT(NARG+100), TABLE(NARG+100)

          INTEGER   INDEX(32)
          REAL*8    WEIGHT(32)
          LOGICAL   MFLAG
C
          INTEGER I,K,N
          INTEGER LOCA,LOCB,LOCC
          INTEGER LMAX,LMIN
          INTEGER ISTEP,KNOTS,NDIM,ISHIFT
          INTEGER LGFILE
          REAL*8 X,H,ETA, DX
C
C----------------------------------------------
          DFINT  =  0.
          IF(NARG .LT. 1  .OR.  NARG .GT. 5)  GOTO 300
          LMAX      =  0
          ISTEP     =  1
          KNOTS     =  1
          INDEX(1)  =  1
          WEIGHT(1) =  1.
          DO 100    N  =  1, NARG
             X     =  ARG(N)
             NDIM  =  NENT(N)
             LOCA  =  LMAX
             LMIN  =  LMAX + 1
             LMAX  =  LMAX + NDIM
             IF(NDIM .GT. 2)  GOTO 10
             IF(NDIM .EQ. 1)  GOTO 100
             H  =  X - ENT(LMIN)
             IF(H .EQ. 0.)  GOTO 90
             ISHIFT  =  ISTEP
             IF(X-ENT(LMIN+1) .EQ. 0.)  GOTO 21
             ISHIFT  =  0
             ETA     =  H / (ENT(LMIN+1) - ENT(LMIN))
             GOTO 30
  10         LOCB  =  LMAX + 1
  11         LOCC  =  (LOCA+LOCB) / 2
C
C Wow.  A computed goto.  Amazing.
C
             DX = X-ENT(LOCC)
             IF( DX .LT. 0.0  ) GOTO 12
             IF( DX .EQ. 0.0  ) GOTO 20
             IF( DX .GT. 0.0  ) GOTO 13
ccc             IF(X-ENT(LOCC))  12, 20, 13   ! obsolete


  12         LOCB  =  LOCC
             GOTO 14
  13         LOCA  =  LOCC
  14         IF(LOCB-LOCA .GT. 1)  GOTO 11
             LOCA    =  MIN0( MAX0(LOCA,LMIN), LMAX-1 )
             ISHIFT  =  (LOCA - LMIN) * ISTEP
             ETA     =  (X - ENT(LOCA)) / (ENT(LOCA+1) - ENT(LOCA))
             GOTO 30
  20         ISHIFT  =  (LOCC - LMIN) * ISTEP
  21         DO 22  K  =  1, KNOTS
                INDEX(K)  =  INDEX(K) + ISHIFT
  22            CONTINUE
             GOTO 90
  30         DO 31  K  =  1, KNOTS
                INDEX(K)         =  INDEX(K) + ISHIFT
                INDEX(K+KNOTS)   =  INDEX(K) + ISTEP
                WEIGHT(K+KNOTS)  =  WEIGHT(K) * ETA
                WEIGHT(K)        =  WEIGHT(K) - WEIGHT(K+KNOTS)
  31            CONTINUE
             KNOTS  =  2*KNOTS
  90         ISTEP  =  ISTEP * NDIM
 100         CONTINUE
          DO 200    K  =  1, KNOTS
             I  =  INDEX(K)
             DFINT  =  DFINT + WEIGHT(K) * TABLE(I)
 200         CONTINUE
          RETURN
 300      CONTINUE

c+SELF,IF=xxCERNLIB.
c          CALL KERMTR('E104.1',LGFILE,MFLAG,RFLAG)
c+SELF.
          IF(MFLAG) THEN
             IF(LGFILE .EQ. 0) THEN
                WRITE(*,1000) NARG
             ELSE
                WRITE(LGFILE,1000) NARG
             ENDIF
          ENDIF

c+SELF,IF=xxCERNLIB.
c          IF(.NOT. RFLAG) CALL ABEND
c+SELF.
          RETURN
1000      FORMAT( 7X,'FUNCTION DFINT ... NARG = ',I6,
     +              ' NOT WITHIN RANGE')
          END


C =========================
CDECK  ID>,  POLINT8. 
C
C snana.car,v 1.595 2012/05/04 01:13:13
C
C
C Revision 1.1.1.1  1996/02/15 17:48:35  mclareni
C Kernlib
C
C Sep 2011: change to double precision
C
C #include "kernnum/pilot.h"
      SUBROUTINE POLINT8(F,ARG,MMMM,Z,SUM)
C         NEW VERSION OF E100 POLINT WRITTEN BY F.JAMES     DEC. 1976
C         LIMITED TO ORDER 19  (20 POINTS)  BY DIMENSION OF COF
C         BUT SUCH INTERPOLATION IS ALREADY UNSTABLE FOR ORDER 10

      IMPLICIT NONE

C subroutine args
      INTEGER MMMM
      DOUBLE PRECISION F(MMMM), ARG(MMMM), Z, SUM

c local var
      DOUBLE PRECISION COF(20)
      INTEGER M, MM, I, J, JNDEX, INDEX, LGFILE

      LOGICAL MFLAG
C ---------- BEGIN ----------
      IF(MMMM .LT. 2) GOTO 1900
      MM = MIN0(MMMM, 20)
      M = MM - 1
      DO 1780 I= 1, MM
         COF(I) = F(I)
 1780 CONTINUE
cc xxx obsolete  1780    COF(I) = F(I)

      DO 1800 I= 1, M
      DO 1790 J= I, M
         JNDEX = MM - J
         INDEX = JNDEX + I
         COF(INDEX) = (COF(INDEX)-COF(INDEX-1))/(ARG(INDEX)-ARG(JNDEX))
 1790 CONTINUE
 1800 CONTINUE
      SUM = COF(MM)
      DO 1810 I= 1, M
         INDEX = MM - I
         SUM = (Z-ARG(INDEX))*SUM + COF(INDEX)
 1810 CONTINUE
      RETURN
 1900 CONTINUE

c+SELF,IF=xxCERNLIB.
c      CALL KERMTR('E100.1', LGFILE, MFLAG, RFLAG)
c+SELF.
      IF(MFLAG) THEN
         IF(LGFILE .EQ. 0) THEN
            WRITE(*,2000) MMMM
         ELSE
            WRITE(LGFILE,2000) MMMM
         ENDIF
      ENDIF

c+SELF,IF=xxCERNLIB.
c      IF(.NOT. RFLAG) CALL ABEND
c+SELF.

      RETURN
 2000 FORMAT( 7X, 'SUBROUTINE POLINT8 ... K =', I6,
     +        ' IS LESS THAN 2')
      END



C ======================================
CDECK  ID>,  FIRSTBIN_INTERP. 
      INTEGER FUNCTION FIRSTBIN_INTERP (
     &   VALUE      ! (I) value to find bin for
     &  ,RANGE      ! (I) allowed range for VALUE
     &  ,BINSIZE    ! (I) binsize for RANGE
     &    )

c
c Return first bin to use for interpoliation.
c Asumes interp is done with 3 bins, where 2nd
c bin contains VALUE.
c
c ------------------------------

      IMPLICIT NONE
      REAL  VALUE, RANGE(2), BINSIZE  ! (I)

c local args

      INTEGER ibin_cen, ibin_start, NBIN
      REAL dif

C ----------------- BEGIN ------------

      FIRSTBIN_INTERP  = -9

      dif      = value - range(1)
      ibin_cen = int ( (dif / binsize) + 0.5 ) + 1

      dif      = range(2) - range(1) + binsize/10000.
      NBIN     = int( dif / binsize ) + 1

c find starting bin for grid interpolation

      if ( ibin_cen .LE. 1 ) then
          ibin_start = 1
      else if ( ibin_cen .GE. NBIN ) then
          ibin_start = NBIN - 2
      else
          ibin_start = ibin_cen - 1   ! nominal case
      endif

      FIRSTBIN_INTERP  = ibin_start

      RETURN
      END     ! end FIRSTBIN_INTERP


C ==================================================
CDECK  ID>,  LCUTVAR. 
      LOGICAL FUNCTION LCUTVAR ( var, icut, VBOSE )
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      REAL    VAR   ! (I) variable to  test cutwin
      INTEGER ICUT  ! (I) points to cutwin
      LOGICAL VBOSE ! (I) T=> print PASS or FAIL for each cut

c local var

      INTEGER ITMP
      CHARACTER CTMP*6

C -------------- BEGIN --------------

      LCUTVAR = var .GE. cutwin_var(1,icut) .and.
     &          var .LE. cutwin_var(2,icut)

      IF ( VBOSE ) THEN
          if ( LCUTVAR ) then
             CTMP = 'PASSES'
          else
             CTMP = 'FAILED'
          endif

          ITMP = INDEX(cutvar_name(icut),':') - 1
          ITMP = MIN(ITMP,14)
          write(6,20) cutvar_name(icut)(1:ITMP), var, CTMP
20        format(T10,A18,' = ', G10.3, 1x, A, ' CUT.' )
      ENDIF

      RETURN
      END

C ====================================
CDECK  ID>,  DMPTRACE. 
      SUBROUTINE DMPTRACE ( banner )
      IMPLICIT NONE
      character banner*(*)
      print*,'  XXXXX ', BANNER
      CALL FLUSH(6)
      RETURN
      END


C ========================================
CDECK  ID>,  IPLOTSPLIT. 
      INTEGER FUNCTION IPLOT_JOBSPLIT(NPLOT)
c
c Created Sep 28, 2012 by R.Kessler
c
c For single job, returns IPLOT = NPLOT is the
c incremental (sparse) index. For non-trivial JOBSPLIT input,
c      IPLOT = (NPLOT-1) * NSPLIT_TOT + ISPLIT
c so that the IPLOT are unique among each split job.
c Needed so that snana#fitres plot-macro works on merged
c histo files from split_and_fit.pl script.
c
c -----------------------------

      IMPLICIT NONE

      INTEGER NPLOT  ! (I) sequential plot number for this job

c local variables.


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER NJOBTOT, IJOB, IPLOT

C -------------- BEGIN ---------------

c set default for non-split jobs.
      IPLOT = NPLOT

c check for internal split (mainly for FITS format)
      NJOBTOT = JOBSPLIT(2) ! total number of split jobs
      IJOB    = JOBSPLIT(1) ! do IJOB of NJOBTOT
      IF ( NJOBTOT .GT. 1 ) THEN
        IPLOT = (NPLOT-1) * NJOBTOT + IJOB
      ENDIF

c check for text-format where SPLIT has been done externally
      NJOBTOT = JOBSPLIT_EXTERNAL(2) ! total number of split jobs
      IJOB    = JOBSPLIT_EXTERNAL(1) ! do IJOB of NJOBTOT
      IF ( NJOBTOT .GT. 1 ) THEN
        IPLOT = (NPLOT-1) * NJOBTOT + IJOB
      ENDIF

c load output
      IPLOT_JOBSPLIT = IPLOT

      RETURN
      END

C =============================================
CDECK  ID>,  GTSIMTYPE. 
      SUBROUTINE GET_SIMNAME_TYPE(name)
      IMPLICIT NONE
      CHARACTER NAME*(*)
      INTEGER LL

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      NAME = ''
      IF ( .NOT. LSIM_SNANA ) RETURN
      LL = INDEX(SIMNAME_TYPE,' ') - 1
      NAME = SIMNAME_TYPE(1:LL) // char(0)  ! Ia, Ib, IIN, etc ...
      RETURN
      END


C =============================
CDECK  ID>,  DOPLOT_SNLC. 
      LOGICAL FUNCTION DOPLOT_SNLC()

C Created Aug 30 2013
C Returns T to make light curve plot for this SN.
C
C ----------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER i, LENTMP
      LOGICAL DOPLOT

C ------------ BEGIN -------------

      DOPLOT = .FALSE.

      if ( OPT_TABLE(ITABLE_SNLCPAK) == 0 ) goto 888  ! Sep 8 2014

      if ( N_SNLC_PLOT < MXLC_PLOT ) THEN
         DOPLOT = .TRUE.
         GOTO 888
      endif

c check list of CCIDs to plot

      DO 100 i = 1, NCCID_PLOT
        LENTMP = INDEX( SNCCID_PLOT(i)//' ', ' ') - 1

        IF ( LENTMP .NE. ISNLC_LENCCID ) GOTO 100

        if ( SNCCID_PLOT(i) .EQ. SNLC_CCID ) then
          DOPLOT = .TRUE.
          GOTO 888
        endif

100   CONTINUE

888   CONTINUE
      DOPLOT_SNLC = DOPLOT

      RETURN
      END

C =============================
CDECK  ID>,  DOPLOT_SPEC. 
      LOGICAL FUNCTION DOPLOT_SPEC()

C Created May 30 2020
C Returns T to make spectra plot(s) for this SN
C
C ----------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER i, LENTMP
      LOGICAL DOPLOT

C ------------ BEGIN -------------

      DOPLOT = .FALSE.
      if ( OPT_TABLE(ITABLE_SPECPAK) == 0 ) goto 888

      if ( N_SNLC_PLOT < MXLC_PLOT ) THEN
         DOPLOT = .TRUE.
         GOTO 888
      endif

c check list of CCIDs to plot

      DO 100 i = 1, NCCID_PLOT
        LENTMP = INDEX( SNCCID_PLOT(i)//' ', ' ') - 1

        IF ( LENTMP .NE. ISNLC_LENCCID ) GOTO 100

        if ( SNCCID_PLOT(i) .EQ. SNLC_CCID ) then
          DOPLOT = .TRUE.
          GOTO 888
        endif

100   CONTINUE

888   CONTINUE
      DOPLOT_SPEC = DOPLOT

      RETURN
      END

C -----------------------------------------
CDECK  ID>,  SPECPLOT. 
      SUBROUTINE SPECPLOT()

c Apr 2019
c Prepare spectra table for plotting (analog of SNLCPLOT)
c Works only for TEXT output; not for HBOOK or ROOT
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


      INTEGER LENCCID, LENTEXT, ispec
      CHARACTER  CCID_forC*(MXCHAR_CCID)
      LOGICAL DOPLOT_SPEC

      EXTERNAL SPECPAK_DATA
C ----------------- BEGIN ---------------

c check if we should make the plot
      IF ( .NOT. DOPLOT_SPEC() ) RETURN

      IF ( MARZFILE_OUT .NE. '' ) RETURN

      LENCCID = ISNLC_LENCCID
      CCID_forC = SNLC_CCID(1:LENCCID) // char(0)

      write(6,10) SNLC_CCID(1:LENCCID)
 10   format(T8,'SPECPLOT: pack CID=',A,' for plotting.')
      call flush(6)

c load each spectrum into SPECPAK C-function util

      DO 100 ispec = 1, NSPECTRUM
         CALL RDSPEC_DRIVER(ispec)  ! Apr 5 2021

         CALL SPECPAK_DATA(
     &         CCID_forC
     &       , ID_SPECTRUM(ispec)
     &       , MJD_SPECTRUM(ispec)
     &       , TOBS_SPECTRUM(ispec)    ! May 7 2019
     &       , TEXPOSE_SPECTRUM(ispec)
     &       , NLAMBIN_SPECTRUM(ispec)
     &       , LAMMIN_SPECTRUM ! array of LAMMIN in each bin
     &       , LAMMAX_SPECTRUM ! array of LAMMAX in each bin
     &       , FLAM_SPECTRUM
     &       , FLAMERR_SPECTRUM
     &       , LENCCID )
 100     CONTINUE

c write out spectrum to TEXT table (HBOOK,ROOT not enabled)
      IF ( NSPECTRUM > 0 ) then
         CALL SPECPAK_FILL(CCID_forC, LENCCID)
      ENDIF

      RETURN
      END  ! SPECPLOT


C ==============================================
CDECK  ID>,  CHECK_DUPLMJD. 
      SUBROUTINE CHECK_DUPLICATE_MJDBAND(iep)

c Created Jun 13, 2017
c print & count error if current MJD & BAND is the same
c as previous epoch.

      IMPLICIT NONE

      INTEGER IEP ! (I) epoch index

c local var

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      REAL*8 MJD, MJD_LAST
      INTEGER IFILTOBS, IFILTOBS_LAST, i
      CHARACTER CFILT*2

c ---------------- BEGIN --------------

cc      IF ( .NOT. ABORT_ON_DUPLMJD  ) RETURN
      IF ( IEP <= 1 ) RETURN

      MJD      = SNLC8_MJD(IEP)
      MJD_LAST = SNLC8_MJD(IEP-1)
      IFILTOBS = ISNLC_IFILT_OBS(IEP)
      IFILTOBS_LAST = ISNLC_IFILT_OBS(IEP-1)

      IF ( MJD      .NE. MJD_LAST      ) RETURN
      IF ( IFILTOBS .NE. IFILTOBS_LAST ) RETURN

      N_DUPLICATE_MJD = N_DUPLICATE_MJD + 1

c check if this MJD was already flagged as duplicate
      DO i = 1, min(200,NSTORE_DUPLICATE_MJD)
        IF ( MJD .EQ. DUPLICATE_MJDLIST(i) ) RETURN
      ENDDO

      NSTORE_DUPLICATE_MJD = NSTORE_DUPLICATE_MJD + 1

      if ( NSTORE_DUPLICATE_MJD < 200 ) then
         DUPLICATE_MJDLIST(NSTORE_DUPLICATE_MJD) = MJD
         CFILT = filtdef_string(ifiltobs:ifiltobs)
         write(6,666) SNLC_CCID(1:ISNLC_LENCCID), MJD, CFILT,
     &        SNLC_FIELDLIST
666      format(/,T5,'*** DUPLICATE MJD WARNING *** CID=',A, 3x,
     &        'MJD=', F9.3, 3x, 'BAND=', A, 2x,'FIELD=',A6, /)
         CALL FLUSH(6)
      endif

      RETURN
      END


C =======================
CDECK  ID>,  TABLE_OUTLIER. 
      SUBROUTINE TABLE_OUTLIER(IDTABLE,IFLAG)
C
C Created Mar 17 2021
C Create and fill table for OUTLIER fluxes w.r.t, SIM truth or LC model fit.
C Goal is to replace outlier option in sntable_dump so that making
C OUTLIER table is a 1-step process (snana.exe) instead of 2 steps
C (snana.exe + sntable_dump.py)
C
c Aug 11 2021: check SBMAG cut

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


      INTEGER IDTABLE  ! (I) table ID
      INTEGER IFLAG    ! (I) see IFLAG_XXX params

c local var

      INTEGER   LENNAME, LENFMT, NEWMJD, EPMIN, EPMAX, EP, BIT
      INTEGER   IFILTOBS, IFILT
      LOGICAL   DOFILL_TABLE, LCUT_NSIG, LCUT_FTRUE, LCUT_SBMAG
      REAL      NSIG, FTRUE, SBMAG, FLUXCAL_FIT, FLUXCAL_ERR_FIT
      CHARACTER NAME_forC*40, TEXTFMT*20, TEXTFMT_forC*20, FNAM*14

      REAL  NSIG_OUTLIER_FIT  ! function
      EXTERNAL  SNTABLE_CREATE, SNTABLE_FILL
C ---------------- BEGIN -----------------

      FNAM = 'TABLE_OUTLIER'

c for snana job, must be sim from either SNANA or FAKE
      IF ( ISJOB_SNANA .and. (.NOT. ISJOB_SIM)  ) THEN
         c1err = 'Cannot make OUTLIER table for ' //
     &           'real data using snana.exe.'
         c2err = 'Process SIM or FAKES; or run LC fit on real data'
         CALL MADABORT(FNAM, c1err, c2err)
      ENDIF

c FIT outliers work on real data or sim, so error check not needed.


      IF ( IFLAG .EQ. IFLAG_INI ) THEN

         OUTLIER_TABLE_NAME  = 'OUTLIER'
         LENNAME   = INDEX(OUTLIER_TABLE_NAME, ' ') - 1
         NAME_forC = OUTLIER_TABLE_NAME(1:LENNAME) // char(0)

         TEXTFMT  = TEXTFORMAT_TABLE(ITABLE_OUTLIER)
         LENFMT   = INDEX(TEXTFMT, ' ') - 1
         TEXTFMT_forC = TEXTFMT(1:LENFMT) // char(0)

         CALL SNTABLE_CREATE(IDTABLE, NAME_forC, TEXTFMT_forC,
     &          LENNAME,LENFMT)  ! C fun

         CALL INIT_TABLE_OUTLIERVAR(IDTABLE, 'OUTLIER')

         CALL COUNT_OUTLIERS(0,0)

         RETURN
      ENDIF


c --------------------------
c fill table.

      if ( ISJOB_SNANA ) then
         DOFILL_TABLE = BTEST(CUTFLAG_SNANA,0)
      else
         DOFILL_TABLE = BTEST(CUTFLAG_SNANA,1)
      endif

      NEP_OUTLIER_PEREVT = 0
      IF ( .NOT. DOFILL_TABLE ) RETURN

c   terminate strings for C table-functions (snana.car routine)
      CALL TABLE_STRING_TERMINATION(+1)

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        DO 201 EP = EPMIN, EPMAX
           IFILTOBS   = ISNLC_IFILT_OBS(ep)
           IFILT      = IFILTDEF_INVMAP_SURVEY(IFILTOBS)
           if ( ISNLC_SNRECON_USE(ep) == 0 ) goto 201

           if ( ISJOB_SNANA ) then
              NSIG   = abs(SIM_EPPULL(ep))
              FTRUE  = SIM_EPFLUXCAL(ep)
              SBMAG  = SNHOST_SBMAG(ifilt)
           else
              NSIG   = NSIG_OUTLIER_FIT(ep)
              FTRUE  = 1000.0  ! something guaranteed to pass cut
              SBMAG  = 20.0    ! idem
           endif

           if ( NSIG  < -0.01            ) goto 201
           if ( FTRUE < FTRUECUT_OUTLIER ) goto 201   ! Mar 24 2021

           LCUT_NSIG  = ( NSIG  >= NSIGCUT_OUTLIER  )
           LCUT_FTRUE = ( FTRUE >= FTRUECUT_OUTLIER )
           LCUT_SBMAG = ( SBMAG <= SBMAGCUT_OUTLIER ) ! Aug 2021

           CALL COUNT_OUTLIERS(1,ep)

           if ( LCUT_NSIG .and. LCUT_FTRUE .and. LCUT_SBMAG ) then
              NEP_OUTLIER_TOT    = NEP_OUTLIER_TOT    + 1
              NEP_OUTLIER_PEREVT = NEP_OUTLIER_PEREVT + 1
              CALL LOAD_OUTLIER_VAR(ep)
              CALL SNTABLE_FILL(IDTABLE) ! generic C function
              CALL COUNT_OUTLIERS(2,ep)
           endif
 201    CONTINUE
 200  CONTINUE

      CALL TABLE_STRING_TERMINATION(-1) ! remove termination

      RETURN
      END    ! end TABLE_OUTLIER


C ======================================
CDECK  ID>,  COUNT_OULIERS. 
      SUBROUTINE COUNT_OUTLIERS(OPT,EP)

      IMPLICIT NONE
      INTEGER OPT  ! 0=init, 1=count all, 2=count outliers, 3=print summary
      INTEGER EP   ! epoch index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


      INTEGER IFILTOBS, BIT, PHOTFLAG
      REAL    XNALL(2), XNOUTLIER(2), XNBULK(2)
      REAL    EFF_OUTLIER, EFF_ERR, EFF_BULK, FOM, XX, XXX
      LOGICAL ISBITSET

c ------------ BEGIN -----------

      if ( NSIGCUT_OUTLIER < 1.0 ) RETURN

      IF ( EP > 0 )  THEN
         IFILTOBS   = ISNLC_IFILT_OBS(ep)
         PHOTFLAG   = ISNLC_PHOTFLAG(ep)
      ENDIF

      IF ( OPT == 0 ) THEN
         ! one-time init
         NEP_OUTLIER_TOT = 0
         DO ifiltobs = 1, MXFILT_ALL
            NEP_OUTLIER_CHECK(ifiltobs) = 0  ! total epochs checked per band
            NEP_OUTLIER_FOUND(ifiltobs) = 0  ! Noutlier per band
         ENDDO

         DO BIT = 1, MXBIT_PHOTFLAG
            NEP_OUTLIER_VS_PHOTBIT(1,BIT) = 0
            NEP_OUTLIER_VS_PHOTBIT(2,BIT) = 0
            NEP_ALL_VS_PHOTBIT(1,BIT) = 0
            NEP_ALL_VS_PHOTBIT(2,BIT) = 0
         ENDDO

      ELSE IF ( OPT == 1 ) THEN
         ! passes cuts, but before checking if it's an outlier
         NEP_OUTLIER_CHECK(ifiltobs) = NEP_OUTLIER_CHECK(ifiltobs) + 1

         do bit = 1, MXBIT_PHOTFLAG
            ISBITSET = BTEST(PHOTFLAG,bit-1)
            NEP_ALL_VS_PHOTBIT(1,BIT) = NEP_ALL_VS_PHOTBIT(1,BIT) + 1
            if ( ISBITSET ) then
               NEP_ALL_VS_PHOTBIT(2,BIT) = NEP_ALL_VS_PHOTBIT(2,BIT) + 1
            endif
         ENDDO

      ELSE IF ( OPT == 2 ) THEN
         ! it's an OUTLIER
         NEP_OUTLIER_FOUND(ifiltobs) = NEP_OUTLIER_FOUND(ifiltobs) + 1

         do bit = 1, MXBIT_PHOTFLAG
            ISBITSET = BTEST(PHOTFLAG,bit-1)
            NEP_OUTLIER_VS_PHOTBIT(1,BIT) =
     &      NEP_OUTLIER_VS_PHOTBIT(1,BIT) + 1
            if ( ISBITSET ) then
               NEP_OUTLIER_VS_PHOTBIT(2,BIT) =
     &         NEP_OUTLIER_VS_PHOTBIT(2,BIT) + 1
            endif
         enddo

      ELSE IF ( OPT == 3 ) THEN
         ! print summary
         print*,' '
         write(6,10) NSIGCUT_OUTLIER

 10      format('  PHOTFLAG BIT PERFORMANCE for REJECTING ',
     &             F5.1, ' sigma OUTLIERS:', / )

         print*,'  BIT   EFF(OUTLIER)   1-EFF(BULK)   FoM'
         print*,'  ----------------------------------------- '
         do bit = 1, MXBIT_PHOTFLAG
            XNALL(1)     = float(NEP_ALL_VS_PHOTBIT(1,BIT))
            XNALL(2)     = float(NEP_ALL_VS_PHOTBIT(2,BIT))
            XNOUTLIER(1) = float(NEP_OUTLIER_VS_PHOTBIT(1,BIT))
            XNOUTLIER(2) = float(NEP_OUTLIER_VS_PHOTBIT(2,BIT))
            XNBULK(1)    = XNALL(1) - XNOUTLIER(1) ! not outliers
            XNBULK(2)    = XNALL(2) - XNOUTLIER(2) ! not outliers
            if ( XNALL(2) > 0.0 .and. XNOUTLIER(1) > 0.0 ) then
               EFF_OUTLIER = XNOUTLIER(2) / XNOUTLIER(1)
               XX      = XNOUTLIER(2) * (XNOUTLIER(1) - XNOUTLIER(2))
               XXX     = XNOUTLIER(1) * XNOUTLIER(1) * XNOUTLIER(1)
               EFF_ERR     = sqrt(XX/XXX)
               EFF_BULK    = 1.0 - XNBULK(2) / XNBULK(1)
               FOM         = EFF_OUTLIER * EFF_BULK
               write(6,30) bit-1, EFF_OUTLIER, EFF_ERR, EFF_BULK, FoM
 30            format(T5,I2, 2x, F6.3,' +_', F6.3, 3x, F6.3, 3x, F6.3 )
            endif
         enddo
         call flush(6)
      ENDIF

      RETURN
      END  ! end COUNT_OUTLIERS

C =============================
CDECK  ID>,  INITBOUTVAR. 
      SUBROUTINE INIT_TABLE_OUTLIERVAR(ID, BLOCK)

      IMPLICIT NONE
      INTEGER   ID          ! (I) table ID
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c +CDE,FILTCOM.

C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


      INTEGER
     &   IFILT, IFILT_OBS, ITEXT
     &  ,LENBLOCK, LENLIST, LENNAME, LENV, ipar, ivar

      LOGICAL LTMP, ADDCOL_SETPKMJD
      CHARACTER varlist*100, CTMP*60, CBLOCK*40
      CHARACTER FNAM*22, CFILT*2
      EXTERNAL
     &    SNTABLE_ADDCOL
     &   ,SNTABLE_ADDCOL_int
     &   ,SNTABLE_ADDCOL_flt
     &   ,SNTABLE_ADDCOL_dbl
     &   ,SNTABLE_ADDCOL_str

c ------------ BEGIN ----------

      FNAM = 'INIT_TABLE_OUTLIERVAR'

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5 )
      call flush(6)

      LENBLOCK     = INDEX(BLOCK//' ',' ') - 1
      CBLOCK       = BLOCK(1:LENBLOCK) // char(0)
      LENLIST      = LEN(VARLIST)

c  for CCID, use special variable SNLC_CCID_forC that has char(0)
c  termination so that parsing CCID with C code is easier.

      VARLIST = 'CCID:C*20' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, SNLC_CCID, VARLIST,1,
     &                   LENBLOCK, 20 )

c ROWNUM is easy identifier for CID-MJD-BAND-CCDNUM;
c e.g., pass ROWNUM to script that fetches stamps.
      VARLIST = 'ROWNUM:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NEP_OUTLIER_TOT, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'FIELD:C*12' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, OUTLIER_FIELD, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'MJD:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, OUTLIER_MJD, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'BAND:C*4' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, OUTLIER_BAND, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'IFILTOBS:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, OUTLIER_IFILTOBS, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'CCDNUM:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, OUTLIER_CCDNUM, VARLIST,1,
     &                   LENBLOCK, 20 )

c---
      VARLIST = 'IXPIX:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, OUTLIER_IXPIX, VARLIST,1,
     &                   LENBLOCK, 20 )
      VARLIST = 'IYPIX:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, OUTLIER_IYPIX, VARLIST,1,
     &                   LENBLOCK, 20 )
      VARLIST = 'AREAFRAC:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_AREAFRAC, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'PHOTFLAG:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, OUTLIER_PHOTFLAG, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'FLUXCAL_DATA:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_FLUXCAL_DATA,
     &           VARLIST, 1, LENBLOCK, 20 )

      VARLIST = 'FLUXCAL_ERR_DATA:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_FLUXCAL_ERR_DATA,
     &        VARLIST, 1, LENBLOCK, 20 )

      VARLIST = 'FLUXCAL_ERR_CALC:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK,OUTLIER_FLUXCAL_ERR_CALC,
     &            VARLIST, 1, LENBLOCK, 20 )

      if ( ISJOB_SNANA ) then
         ! outlier w.r.t. true sim/fake flux (SIM_MAGOBS column in data file)
         VARLIST = 'FLUXCAL_TRUE:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_FLUXCAL_TRUE,
     &        VARLIST, 1, LENBLOCK, 20 )
      else
         ! outlier w.r.t. LC fit
         VARLIST = 'FLUXCAL_FIT:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_FLUXCAL_FIT,
     &        VARLIST, 1, LENBLOCK, 20 )

         VARLIST = 'FLUXCAL_ERR_FIT:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_FLUXCAL_ERR_FIT,
     &         VARLIST, 1, LENBLOCK, 20 )

         VARLIST = 'FLUXCAL_ERRTOT_FIT:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_FLUXCAL_ERRTOT_FIT,
     &         VARLIST, 1, LENBLOCK, 20 )
      endif

      VARLIST = 'NSIG:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_NSIG, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'LOGSNR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_LOGSNR, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'SBMAG:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_SBMAG, VARLIST,1,
     &                   LENBLOCK, 20 )

c - - - -
      VARLIST = 'ZP:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_ZP, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'PSF:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_PSF, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'SKYSIG:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_SKYSIG, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'z:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_z, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'TREST:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, OUTLIER_TREST, VARLIST,1,
     &                   LENBLOCK, 20 )

      RETURN
      END   ! end INIT_TABLE_OUTLIERVAR

CDECK  ID>,  SNTABLE_ADDCOL_C. 

CDECK  ID>,  SNTABLE_ADDCOL_I. 

CDECK  ID>,  SNTABLE_ADDCOL_F. 

CDECK  ID>,  SNTABLE_ADDCOL_D. 

C =============================
CDECK  ID>,  LOAD_OUTLIER_VAR. 
      SUBROUTINE LOAD_OUTLIER_VAR(ep)

c Created Mar 17 2021
c Load OUTLIER_XXX variables for epoch 'ep'.
c

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


      INTEGER  ep  ! (I) epoch index to load

      INTEGER IFILT_OBS, IFILT
      CHARACTER BAND*4
      REAL SNR

c ---------- BEGIN ---------

      IFILT_OBS   = ISNLC_IFILT_OBS(ep)
      IFILT       = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
      BAND        = filtdef_string(ifilt_obs:ifilt_obs)

      OUTLIER_MJD          = SNLC8_MJD(ep)
      OUTLIER_IFILTOBS     = IFILT_OBS
      OUTLIER_BAND         = BAND
      OUTLIER_FIELD        = SNLC_FIELD(ep)
      OUTLIER_CCDNUM       = ISNLC_CCDNUM(ep)
      OUTLIER_PHOTFLAG     = ISNLC_PHOTFLAG(ep)
      OUTLIER_FLUXCAL_DATA      = SNLC_FLUXCAL(ep)
      OUTLIER_FLUXCAL_ERR_DATA  = SNLC_FLUXCAL_ERRTOT(ep)
      OUTLIER_FLUXCAL_ERR_CALC  = SNLC_FLUXCAL_ERRCALC(ep)
      OUTLIER_NSIG         = abs(SIM_EPPULL(ep))
      OUTLIER_ZP           = SNLC_ZEROPT(ep)
      OUTLIER_PSF          = SNLC_PSF_SIG1(ep)
      OUTLIER_SKYSIG       = SNLC_SKYSIG(ep)

      SNR  = OUTLIER_FLUXCAL_DATA/OUTLIER_FLUXCAL_ERR_DATA
      OUTLIER_LOGSNR       = LOG10(max(0.1,SNR))

      OUTLIER_SBMAG        = SNHOST_SBMAG(ifilt)

      OUTLIER_IXPIX     = INT(SNLC_XPIX(ep))
      OUTLIER_IYPIX     = INT(SNLC_YPIX(ep))
      OUTLIER_AREAFRAC  = SNLC_AREAFRAC(ep)

      OUTLIER_z         = SNLC_REDSHIFT
      OUTLIER_TREST     = SNLC_TREST(ep)

      IF ( ISJOB_SNANA ) THEN
         ! true flux from SIM_MAGOBS
         OUTLIER_FLUXCAL_TRUE      = SIM_EPFLUXCAL(ep)
      ELSE
         ! get model fit flux
         OUTLIER_FLUXCAL_FIT        = SNLC_FLUXCAL_FIT(ep)
         OUTLIER_FLUXCAL_ERR_FIT    = SNLC_FLUXCAL_ERR_FIT(ep)
         OUTLIER_FLUXCAL_ERRTOT_FIT = SNLC_FLUXCAL_ERRTOT_FIT(ep)
      ENDIF

      IF ( USE_TABLEFILE_ROOT ) THEN
         OUTLIER_BAND = OUTLIER_BAND(1:1) // char(0)
      ENDIF

      RETURN
      END   ! end LOAD_OUTLIER_VAR(ep)


C ===========================================
CDECK  ID>,  NSIG_OUTLIER_FIT. 
      REAL FUNCTION NSIG_OUTLIER_FIT(ep)

c Created Mar 17 2021
c Function returns Nsig = | FLUXCAL_DATA / ERRTOT |
c where ERRTOT^2 = FLUXCAL_ERR_DATA^2 + FLUXCAL_ERR_FIT^2
c Initial use is for OUTLIER table.
c
      IMPLICIT NONE
      INTEGER  ep  ! (I) epoch index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c +CDE,FILTCOM.

C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


      REAL  FLUXCAL_FIT, FLUXCAL_ERR_FIT
      REAL  FLUXCAL_DATA, FLUXCAL_ERR_DATA, SQERR, ERRTOT, NSIG
      LOGICAL REJECT
C --------- BEGIN ---------

      NSIG = 0.0

      CALL GET_FITFLUX(ep, FLUXCAL_FIT, FLUXCAL_ERR_FIT,REJECT)

      FLUXCAL_DATA     = SNLC_FLUXCAL(ep)
      FLUXCAL_ERR_DATA = SNLC_FLUXCAL_ERRTOT(ep)

      IF ( FLUXCAL_ERR_FIT > 0.00001 ) THEN
         SQERR = (FLUXCAL_ERR_FIT  * FLUXCAL_ERR_FIT) +
     &           (FLUXCAL_ERR_DATA * FLUXCAL_ERR_DATA)

         ERRTOT = SQRT(SQERR)
         NSIG   = abs(FLUXCAL_DATA-FLUXCAL_FIT) / ERRTOT
      ELSE
         ERRTOT = FLUXCAL_ERR_DATA
         NSIG   = -9.0  ! epoch not used
      ENDIF

c      print*,' xxx ep, DIF/ERR = ',
c     &    ep, (FLUXCAL_DATA-FLUXCAL_FIT), '/', ERRTOT, NSIG

c load fit flux info to global so that it can be used elsewhere
      SNLC_FLUXCAL_FIT(ep)        = FLUXCAL_FIT
      SNLC_FLUXCAL_ERR_FIT(ep)    = FLUXCAL_ERR_FIT
      SNLC_FLUXCAL_ERRTOT_FIT(ep) = ERRTOT

c set function value
      NSIG_OUTLIER_FIT = NSIG

      RETURN
      END     ! end NSIG_OUTLIER_FIT(ep)

C ==================================
CDECK  ID>,  PR_OUTLIER_SUMMARY. 
      SUBROUTINE PRINT_OUTLIER_SUMMARY()

c Created Mar 17 2021
c print OUTLIER fraction per band to stdout.
c If TEXTFILE_PREFIX is set, prepend top of file with summary
c using clumsy method of writing a separate header file and
c then using system cat command.

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------


C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


c +CDE,SNPAR.
c +CDE,CTRLCOM.
c +CDE,SNLCINP.

      INTEGER IFILT, IFILTOBS, N0, N1, LEN_WHAT
      INTEGER LEN1, LEN2, LEN3, LEN_HEAD
      REAL FRAC
      CHARACTER cfilt*2, TEXT_WHAT*40, CMD_CAT*200, CMD_MOVE*200
      CHARACTER TEXTFILE*200, TMP_HEADER_FILE*200, LINE*60, LINE2*60
      LOGICAL   PREPEND_TEXTFILE

C ---------- BEGIN -----------

      call count_outliers(3,0)

      PREPEND_TEXTFILE = ( TEXTFILE_PREFIX .NE. ' ' )
      IF ( PREPEND_TEXTFILE ) THEN
c construct name of TEXT file to prepend outlier summary.
c Beware that TEXTFILE is fragile.
         LEN1 = INDEX(TEXTFILE_PREFIX,   ' ' ) - 1
         LEN2 = INDEX(OUTLIER_TABLE_NAME,' ' ) - 1
         TEXTFILE = TEXTFILE_PREFIX(1:LEN1) // '.' //
     &       OUTLIER_TABLE_NAME(1:LEN2) // '.TEXT'
         LEN3 = INDEX(TEXTFILE,' ') - 1
         TMP_HEADER_FILE =
     &       'TMP_HEAD_' // TEXTFILE_PREFIX(1:LEN1) // '.TEXT'
         LEN_HEAD = INDEX(TMP_HEADER_FILE,' ') - 1
         OPEN(UNIT=LUNTMP, FILE=TMP_HEADER_FILE, STATUS='UNKNOWN')
      ENDIF

c - - - - - - -

      IF ( ISJOB_SNANA ) THEN
         TEXT_WHAT  = '|F_data-F_true(SIM)|/Sigma_F'
      ELSE
         TEXT_WHAT  = '|F_data-F_fit|/Sigma_F'
      ENDIF
      LEN_WHAT = INDEX(TEXT_WHAT,' ') - 1

      LINE = '    FLUX-OUTLIER SUMMARY per BAND for '
      write(LINE2,10) TEXT_WHAT(1:LEN_WHAT), NSIGCUT_OUTLIER
 10   format(T5, A, ' > ', F5.2, ' : ' )

      print*, ' '
      print*, LINE
      print*, LINE2
      call flush(6)

      if (PREPEND_TEXTFILE) then
         WRITE(LUNTMP,70) '=========================================='
         WRITE(LUNTMP,70) LINE
         WRITE(LUNTMP,70) LINE2
      endif

 70   format('# ', A)
c - - - - - -

      DO ifilt  = 1, NFILTDEF_SURVEY
         ifiltobs  = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt     = filtdef_string(ifiltobs:ifiltobs)

         N0 = NEP_OUTLIER_CHECK(ifiltobs)
         N1 = NEP_OUTLIER_FOUND(ifiltobs)
         if ( N0 > 0 ) then
            FRAC = FLOAT(N1) / FLOAT(N0)
         else
            FRAC = 0.0
         endif

         write(LINE,20) cfilt, FRAC, N1, N0
 20      format(T8,A1, '-Outlier frac = ', F8.5, 3x,
     &      '(', I6, '/', I6, ')'  )

         print*, LINE
         if (PREPEND_TEXTFILE) WRITE(LUNTMP,70) LINE

      ENDDO

      if(PREPEND_TEXTFILE) then
         WRITE(LUNTMP,70) ' '
         CLOSE(UNIT = LUNTMP)
c finally, use cat to glue header comments and table.
         CMD_CAT = 'cat ' // TEXTFILE(1:LEN3) //
     &         ' >> ' // TMP_HEADER_FILE
         CMD_MOVE = 'mv ' // TMP_HEADER_FILE(1:LEN_HEAD) //  ' ' //
     &           TEXTFILE(1:LEN3)
         CALL SYSTEM(CMD_CAT // ' ; ' // CMD_MOVE)
      endif

      CALL FLUSH(6)

      RETURN
      END   ! end PRINT_OUTLIER_SUMMARY

C ===========================================
CDECK  ID>,  TABLE_SNANA. 
      SUBROUTINE TABLE_SNANA(IDTABLE,IFLAG)
c
c Apr 26 2017: check PRESCALE_TABLE
c
c ------------------------------
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IDTABLE  ! (I) table ID
      INTEGER IFLAG    ! (I) see IFLAG_XXX params

c local var

      LOGICAL   DO_FILL, LPS
      REAL*8    PS
      INTEGER   LENNAME, LENFMT
      CHARACTER NAME*40, TEXTFMT*20, TEXTFMT_forC*20, FNAM*12
      EXTERNAL SNTABLE_CREATE, SNTABLE_FILL

      LOGICAL REJECT_PRESCALE  ! function

C -------------------- BEGIN -----------------
      FNAM = 'TABLE_SNANA'

      IF ( IFLAG .EQ. IFLAG_INI ) THEN

         NAME     = 'SNANA' // char(0)
         LENNAME  = INDEX(NAME,    ' ') - 1

         TEXTFMT  = TEXTFORMAT_TABLE(ITABLE_SNANA)
         LENFMT   = INDEX(TEXTFMT, ' ') - 1
         TEXTFMT_forC = TEXTFMT(1:LENFMT) // char(0)

         CALL SNTABLE_CREATE(IDTABLE,NAME,TEXTFMT_forC,
     &          LENNAME,LENFMT)  ! C fun

c make table of scalars
         CALL INIT_TABLE_SNANAVAR(IDTABLE, 'SNANA', 1)

c check option to store variables for each obs (Mar 2015)
         IF ( OPT_TABLE(ITABLE_SNANA) .EQ. 2 ) THEN
           CALL INIT_TABLE_SNOBSVAR(IDTABLE, 'SNOBS')
         ENDIF

         IF ( OPT_TABLE(ITABLE_SNANA) .EQ. 4 ) THEN ! Jan 2019
           CALL INIT_TABLE_SIM_MAGOBS(IDTABLE, 'MODELMAG')
         ENDIF

c for sims ...

         CALL INIT_TABLE_SIMVAR(IDTABLE, 'SIM')
         CALL FLUSH(6)
         RETURN
      ENDIF

c --------------------------
c fill table.

      DO_FILL = .FALSE.

      IF ( CUTMASK_SNANA_TABLE == 63 )
     &          DO_FILL = .TRUE.   ! default --> include everything

c check subset options
      IF (CUTFLAG_SNANA == 0 .and. CUTMASK_SNANA_TABLE == 0 )
     &          DO_FILL = .TRUE.
      IF( IAND(CUTFLAG_SNANA,CUTMASK_SNANA_TABLE) > 0 )
     &          DO_FILL = .TRUE.


      IF ( DO_FILL ) THEN

c       terminate strings for C table-functions (snana.car routine)
        CALL TABLE_STRING_TERMINATION(+1)

c check option to store MODEL-MAG on epoch grid (Feb 2019)
        IF ( OPT_TABLE(ITABLE_SNANA) .EQ. 4 ) THEN
           CALL LOAD_TABLE_SIM_MAGOBS()
        ENDIF

        PS  = DBLE(PRESCALE_TABLE(ITABLE_SNANA))
        LPS = REJECT_PRESCALE(NCALL_SNANA_DRIVER,PS)
        IF ( .not. LPS ) THEN
          CALL SNTABLE_FILL(IDTABLE)  ! generic C function
        ENDIF

        CALL TABLE_STRING_TERMINATION(-1)  ! remove termination
      ENDIF

      RETURN
      END    ! end of TABLE_SNANA

C =====================================
CDECK  ID>,  TBSNVAR. 
      SUBROUTINE INIT_TABLE_SNANAVAR(ID,BLOCK,IFLAG)
c
c Created Feb 1, 2013
c
c Initialize variables for snana-analysis table.
c Call generic function SNTABLE_ADDCOL() that loads a table
c for each selected format: CERNLIB, ROOT, HDF5 ...
c
c IFLAG = 1 => regular SNANA variables
c IFLAG = 2 => use _FIT variables instead (if they exist) since
c              post-fit variables may be different than the
c              original SNANA variables (e.g., SNRMAX3 can change
c              if a filter is excluded from a fit.
c
c
c May 31 2016: add zCMB[ERR] to text file and remove legacy "z,zerr"
c              from text file [since z=zHELIO]
c
c Jan  8 2018: write zHEL[ERR] to text file
c Mar  9 2018: add PHOTPROB info, MIN and Nepochs
c Mar 10 2019: add HOST_OBJID with BLOCK_LL for long long int
c May 23 2019: bug fix: book HOST_RA[DEC] as double instead of float.
c Feb 20 2020: write MWEBV to TEXT table.
c May 14 2020: add zFLAG
c Mar 14 2021: always include PKMJDINI in TEXT output
c Mar 19 2021: add NEP_OUTLIER if OUTLIER table is defined
c Aug 13 2021: include HOST_SBMAG, and HOST_SB -> HOST_SBFLUXCAL
c Sep 09 2023: update to write 2nd HOST match.
c
c -------------------------------------------------------------

      IMPLICIT NONE
      INTEGER   ID          ! (I) table ID
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)
      INTEGER   IFLAG       ! (I) SNANA or _FIT variables

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,USRTAGCM. inserted below by ypatchy. 

      INTEGER MXUSERTAG
      PARAMETER ( MXUSERTAG = 1000 ) ! max number of user tags

      INTEGER
     &   N_USERTAGS           ! number of tags in USERTAGS_FILE
     &  ,USERTAG_VALUELIST(MXUSERTAG)  ! list of user tags
     &  ,USERTAG                   ! USERTAG value  for current SN

      BYTE
     &   USERTAG_USED(MXUSERTAG)   ! mark when each USERTAG is used

      CHARACTER
     &   USERTAG_CCIDLIST(MXUSERTAG)*(MXCHAR_CCID)  ! list of CCID

      COMMON / USERTAGCOM /
     &   N_USERTAGS, USERTAG_VALUELIST, USERTAG_CCIDLIST
     &  ,USERTAG, USERTAG_USED



C +CDE,PRIVCOM. inserted below by ypatchy. 

c Nov 2012: PRIVATE_VAR variables in data files
c Aug 2014: MXVAR_PRIVATE -> 28 (was 20)

      REAL*8  PRIVATE_NULL
      PARAMETER ( PRIVATE_NULL = -999.0909 )

      INTEGER
     &   NVAR_PRIVATE        ! Number of private  variables
     &  ,NCUT_PRIVATE

c for  the following header key
c    PRIVATE(BLA): 44.4
c we have
c   VARANME = 'BLA'
c   KEYWORD = 'PRIVATE(BLA)'
c   VALUE   = 44.4

      CHARACTER
     &   PRIVATE_VARNAME(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)
     &  ,PRIVATE_KEYWORD(MXVAR_PRIVATE)*(MXCHAR_FILEWORD)

      REAL*8
     &    PRIVATE_VALUE(MXVAR_PRIVATE)    ! value for each var
     &   ,PRIVATE_CUTWIN(2,MXVAR_PRIVATE) ! cut-window on each var

      INTEGER USE_PRIVATE_CUTWIN(MXVAR_PRIVATE)  ! 1=cutwin, -1=veto

      COMMON / PRIVATE_VARCOM  /
     &     NVAR_PRIVATE, PRIVATE_VARNAME, PRIVATE_KEYWORD
     &    ,NCUT_PRIVATE, USE_PRIVATE_CUTWIN

      COMMON / PRIVATECOM8 / PRIVATE_VALUE, PRIVATE_CUTWIN



C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


C +CDE,REQEPCOM. inserted below by ypatchy. 
      CHARACTER FILTLIST_REQEP*(MXFILT_ALL)
      INTEGER NFILT_REQEP, IFILTLIST_REQEP(MXFILT_ALL)
      REAL  TRANGE_REQEP(3), SNRMIN_REQEP
      LOGICAL ISFRAME_REST_REQEP, ISFRAME_OBS_REQEP

      COMMON / REQEPINP /
     &    NFILT_REQEP, FILTLIST_REQEP, IFILTLIST_REQEP
     &   ,TRANGE_REQEP, SNRMIN_REQEP
     &   ,ISFRAME_REST_REQEP, ISFRAME_OBS_REQEP

      REAL NDAYS_ABOVE_SNRMIN_REQEP
      COMMON / REQEPCOM / NDAYS_ABOVE_SNRMIN_REQEP



C +CDE,OUTLIERCOM. inserted below by ypatchy. 

      INTEGER MXFILT_OUTLIER
      PARAMETER ( MXFILT_OUTLIER = 100) ! avoid includig FILTCOM

      CHARACTER OUTLIER_TABLE_NAME*12

      REAL
     &   NSIGCUT_OUTLIER    ! e.g., SNTABLE_LIST='OUTLIER(nsig:3.5)'
     &  ,FTRUECUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(Ftrue:0.0)'
     &  ,SBMAGCUT_OUTLIER   ! e.g., SNTABLE_LIST='OUTLIER(sbmag:25.0)

      REAL*8 OUTLIER_MJD
      REAL*4
     &   OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT  ! data + fit errors in quadrature
     &  ,OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST  ! for LC FIT only

      INTEGER
     &    NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &   ,NEP_OUTLIER_CHECK(MXFILT_OUTLIER)  ! total epochs checked per band
     &   ,NEP_OUTLIER_FOUND(MXFILT_OUTLIER)  ! Noutlier per band
     &   ,OUTLIER_IFILTOBS, OUTLIER_CCDNUM, OUTLIER_PHOTFLAG
     &   ,OUTLIER_IXPIX, OUTLIER_IYPIX

      CHARACTER OUTLIER_BAND*4, OUTLIER_FIELD*20

      COMMON / OUTLIERCUTS /
     &   NSIGCUT_OUTLIER, FTRUECUT_OUTLIER, SBMAGCUT_OUTLIER

      COMMON / OUTLIERCOM8 / OUTLIER_MJD
      COMMON / OUTLIERCOM4 / NEP_OUTLIER_TOT, NEP_OUTLIER_PEREVT
     &  ,NEP_OUTLIER_CHECK, NEP_OUTLIER_FOUND, OUTLIER_TABLE_NAME
     &  ,OUTLIER_FLUXCAL_DATA, OUTLIER_FLUXCAL_ERR_DATA
     &  ,OUTLIER_FLUXCAL_ERR_CALC
     &  ,OUTLIER_FLUXCAL_TRUE
     &  ,OUTLIER_FLUXCAL_FIT, OUTLIER_FLUXCAL_ERR_FIT
     &  ,OUTLIER_FLUXCAL_ERRTOT_FIT
     &  ,OUTLIER_IXPIX, OUTLIER_IYPIX, OUTLIER_AREAFRAC
     &  ,OUTLIER_ZP, OUTLIER_NEA, OUTLIER_PSF, OUTLIER_SKYSIG
     &  ,OUTLIER_NSIG, OUTLIER_LOGSNR, OUTLIER_SBMAG
     &  ,OUTLIER_z, OUTLIER_TREST
     &  ,OUTLIER_IFILTOBS, OUTLIER_BAND, OUTLIER_FIELD
     &  ,OUTLIER_CCDNUM, OUTLIER_PHOTFLAG

c efficiency for PHOTFLAG bits

      INTEGER
     &   NEP_OUTLIER_VS_PHOTBIT(2,MXBIT_PHOTFLAG)    ! 1=TOT, 2=bit set
     &  ,NEP_ALL_VS_PHOTBIT(2,MXBIT_PHOTFLAG)        ! 1=TOT, 2=bit set

      COMMON /OUTLIER_PHOTPROB /
     &  NEP_OUTLIER_VS_PHOTBIT, NEP_ALL_VS_PHOTBIT


C +CDE,TRUECHI2COM. inserted below by ypatchy. 

c for fakes and sim, compute sum[F-Ftrue]^2/sigma^2 per band
c The zeroth element is all bands together.

      REAL
     &   CHI2_TRUEFLUX(0:MXFILT_ALL)
     &  ,PROB_TRUEFLUX(0:MXFILT_ALL)

      INTEGER NDOF_TRUEFLUX(0:MXFILT_ALL)

      COMMON /  TRUECHI2COM /
     &   NDOF_TRUEFLUX, CHI2_TRUEFLUX, PROB_TRUEFLUX


      INTEGER
     &   IFILT, IFILT_OBS, ITEXT, ITEXT2, IGAL
     &  ,LENBLOCK, LENLIST, LENNAME, LENV, ipar, ivar

      LOGICAL LTMP, ADDCOL_SETPKMJD
      CHARACTER varlist*1000, CTMP*60, CBLOCK*40
      CHARACTER FNAM*20, VARNAME*40, CFILT*2
      EXTERNAL
     &   SNTABLE_ADDCOL
     &  ,SNTABLE_ADDCOL_int
     &  ,SNTABLE_ADDCOL_flt
     &  ,SNTABLE_ADDCOL_dbl
     &  ,SNTABLE_ADDCOL_str

C ---------------- BEGIN ------------

      FNAM = 'INIT_TABLE_SNANAVAR'

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5 )
      call flush(6)

      LENBLOCK     = INDEX(BLOCK//' ',' ') - 1
      CBLOCK       = BLOCK(1:LENBLOCK) // char(0)
      LENLIST      = LEN(VARLIST)

c check filter list for filter-dependent columns (Feb 2017)
      ADDCOL_FILTERS = SURVEY_FILTERS  ! default
      IF ( NFILT_REMAP_TABLE > 0 ) THEN
         ADDCOL_FILTERS = FILTLIST_REMAP_TABLE
      ENDIF

      LTMP = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_SAVEPAR)
      ADDCOL_SETPKMJD = ( LTMP .and. OPT_SETPKMJD > 0 )

c - - - - - - ID variables - - - - - -

      VARLIST = 'CID:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SNLC_CID, VARLIST,0,
     &                   LENBLOCK, 20 )

c  for CCID, use special variable SNLC_CCID_forC that has char(0)
c  termination so that parsing CCID with C code is easier.

      VARLIST = 'CCID:C*20' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, SNLC_CCID, VARLIST,1,
     &                   LENBLOCK, 20 )

c Aug 2022: check optional user-column; e.g., to tag magshift value
      if ( SNTABLE_APPEND_VARNAME .NE. '' ) then
         LENV = INDEX(SNTABLE_APPEND_VARNAME,' ') - 1
         VARLIST = SNTABLE_APPEND_VARNAME(1:LENV) // ':F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK,SNTABLE_APPEND_VALUE,
     &              VARLIST,1,      LENBLOCK, 20 )
      endif
c to do: when combined low-z is ready change IDSURVEY -> IDSUBSURVEY,
c but keep same name 'IDSURVEY'
      VARLIST = 'IDSURVEY:I' //  char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, IDSUBSURVEY, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'TYPE:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_TYPE, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'NFIELD_OVP:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_NFIELD_OVP,
     &               VARLIST, 0,    LENBLOCK, 20 )

      VARLIST = 'FIELD:C*20' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, SNLC_FIELDLIST, VARLIST,1,
     &                   LENBLOCK, 20 )

c Feb 15 2018: remove condition on CCDNUM
      ITEXT = 0 ;     IF(NCCDNUM_LIST>0) ITEXT = 1
      VARLIST = 'CCDNUM:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_CCDNUM(1),
     &            VARLIST,ITEXT,       LENBLOCK, 20 )

c -------------------------------------------
c CUTFLAG_SNANA is a mask as follows:
c 0    -> failed SNANA cuts
c bit0 -> passed SNANA cuts
c bit1 -> passed FIT cuts (i.e, valid fit + re-applied snana cuts)

      VARLIST = 'CUTFLAG_SNANA:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, CUTFLAG_SNANA, VARLIST,1,
     &                   LENBLOCK, 20)

c -------------------------------------------
c ERRFLAG_FIT = -9 -> no fit, just SNANA job
c ERRFLAG_FIT =  0 -> no fitting errors.
c ERRFLAG_FIT >  0 -> fit failed, see ERRFLAG codes in fitting program.

      ITEXT = 0
      ITEXT=1
      VARLIST = 'ERRFLAG_FIT:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ERRFLAG_FIT,
     &              VARLIST,ITEXT,   LENBLOCK, 20 )

c --------------------------------------------
      IF ( N_USERTAGS .GT. 0) then
        VARLIST = 'USERTAG:I'  // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, USERTAG, VARLIST,1,
     &                   LENBLOCK, 20)
      endif

      VARLIST = 'RA:D,DEC:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, SNLC8_RA, VARLIST,0,
     &                   LENBLOCK, 20 )

      VARLIST = 'AREAFRAC_AVG:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_AREAFRAC_AVG,
     &              VARLIST,0,  LENBLOCK, 20 )

c -- NEPOCH ( Aug 2013)

      VARLIST = 'NEPOCH:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_NEPOCH_STORE,
     &               VARLIST,0,  LENBLOCK, 20 )

      VARLIST = 'NEPOCH_BADPHOT:I' // char(0)      ! added Jun 2016
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NEPOCH_BADPHOT, VARLIST, 0,
     &                   LENBLOCK, 20 )


c Mar 2018: add info about PHOTPROB
      VARLIST = 'NEPOCH_PHOTPROB:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_NEPOCH_PHOTPROB,
     &            VARLIST,0,  LENBLOCK, 20 )

      VARLIST = 'PHOTPROB_MIN:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_PHOTPROB_MIN,
     &                VARLIST,0,   LENBLOCK, 20 )

c Sep 2018: add optonal info about detections
c Nov 2020: write to TEXT file
      IF ( PHOTFLAG_DETECT > 0 ) THEN
         VARLIST = 'NEPOCH_DETECT:I' // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_NEPOCH_DETECT,
     &                VARLIST,1, LENBLOCK, 20 )
         VARLIST = 'TLIVE_DETECT:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_TLIVE_DETECT,
     &              VARLIST,1,   LENBLOCK, 20 )
      ENDIF


      IF ( OPT_TABLE(ITABLE_OUTLIER) > 0 ) THEN
         VARLIST = 'NEPOCH_OUTLIER:I' // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NEP_OUTLIER_PEREVT,
     &            VARLIST,1,   LENBLOCK, 20 )
      ENDIF
c - - - - -  redshift - - - - -

      VARLIST = 'zHEL:F,zHELERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_ZHELIO, VARLIST, 1,
     &                   LENBLOCK, 20 )

      VARLIST = 'zCMB:F,zCMBERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_ZCMB, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'zHD:F,zHDERR:F' // char(0)  ! Hubble diagram redshift
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_ZHD, VARLIST,1,
     &                   LENBLOCK, 20 )

      VARLIST = 'zFLAG:I' // char(0)  ! z-quality flag (May 2020)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_zFLAG, VARLIST, 0,
     &                   LENBLOCK, 20 )

c z = zCMB for spec z, but for photo-z fit z & zERR are the original
c data redshifts to allow plotting zHD-z resids
      VARLIST = 'z:F,zERR:F'  // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_REDSHIFT, VARLIST, 0,
     &                   LENBLOCK, 20)

c tack on VPEC
      VARLIST = 'VPEC:F,VPECERR:F'  // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_VPEC, VARLIST, 1,
     &                       LENBLOCK, 20 )

c - - - - -  Galactic extinction - - - -  -
c Feb 6 2020: write MWEBV to TEXT (but not the error)

      VARLIST = 'MWEBV:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_MWEBV, VARLIST, 1,
     &                   LENBLOCK, 20 )

      VARLIST = 'MWEBVERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_MWEBV, VARLIST, 0,
     &                   LENBLOCK, 20 )

c - - - - - - HOST GALAXY - - - -
      ITEXT = 0
      if ( WRTABLEFILE_HOST_TEXT .or. WRTABLEFILE_HOST2_TEXT ) ITEXT=1

      ITEXT2 = 0
      if ( WRTABLEFILE_HOST2_TEXT ) ITEXT2=1  ! for 2nd host only

      VARLIST =  'HOST_NMATCH:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SNHOST_NMATCH,
     &              VARLIST,ITEXT,   LENBLOCK, 20 )
      VARLIST =  'HOST_NMATCH2:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SNHOST_NMATCH2,
     &              VARLIST,ITEXT,    LENBLOCK, 20 )

      IGAL = 1
      CALL INIT_TABLE_HOSTVAR(ID, IGAL, ITEXT, BLOCK)

      IGAL = 2
      CALL INIT_TABLE_HOSTVAR(ID, IGAL, ITEXT2, BLOCK)


c Apr 2022
c store host surface brightness if SB exists or host-mag exists.
c The host-mag check is a safety feature in case SB is undefined.
c E.g., DES event 1248110 has SBFLUX=-999 even though host mags are
c all in the 21-22 range. Likely a subtle problem measuring SBFLUX
c on the template image.

      IF ( EXIST_SNHOST_SB .OR. EXIST_SNHOST_MAGOBS) THEN
c        HOST_SB -> HOST_SBFLUXCAL
        CALL TABLE_VARLIST_FILTERS('HOST_SBFLUXCAL','F', ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_SNHOST_SBFLUXCAL(1),
     &      VARLIST(1:LENLIST)//char(0), itext, LENBLOCK, LENLIST)

        CALL TABLE_VARLIST_FILTERS('HOST_SBMAG','F', ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_SNHOST_SBMAG(1),
     &      VARLIST(1:LENLIST)//char(0), itext, LENBLOCK, LENLIST)
      ENDIF


c - - - - -  initial PEAKMJD  - -  -
      ITEXT = 1                       ! default is no TEXT output ...
      VARLIST = 'PKMJDINI:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_SEARCH_PEAKMJD,
     &           VARLIST, ITEXT, LENBLOCK, 20 )

c - - - - time above threshold for REQUIRE_EPOCHS - - - - - -

      IF( NFILT_REQEP > 0 ) THEN
        VARLIST = 'NDAYS_ABOVE_SNRMIN:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, NDAYS_ABOVE_SNRMIN_REQEP,
     &                    VARLIST, 1,       LENBLOCK, 40 )
      ENDIF

c - - - - - max flux per band (May 2016) - - - - - - - - -

        CALL TABLE_VARLIST_FILTERS('FLUXCALMAX','F', ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_FLUXCALMAX(1),
     &      VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)

c ... and the uncertainty (Nov 2022)

        CALL TABLE_VARLIST_FILTERS('FLUXCALMAX_ERR','F',ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_FLUXCALMAX_ERR(1),
     &      VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)

c - - - - - - optional fit-params from PKMJD fit (Oct 20 2014) - - -

      IF ( ADDCOL_SETPKMJD ) THEN
         DO ipar = IPAR_T0, IPAR_A2
            VARNAME = 'FIT_' // PKPARNAME(ipar)
            LENV    = INDEX(VARNAME,' ') - 1
            CALL TABLE_VARLIST_FILTERS(VARNAME(1:LENV),'F',
     &           SURVEY_FILTERS, VARLIST, LENLIST)

            CALL SNTABLE_ADDCOL_flt(ID, CBLOCK,
     &           SNLC_SNANAFIT_PEAKMJD_FITPAR(1,ipar),
     &           VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)
         ENDDO

c ----------------------------
c  PKMJD per filter

         DO 222 ifilt  = 1, NFILTDEF_SURVEY
            ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
            cfilt     = filtdef_string(ifilt_obs:ifilt_obs)

            IF( IFILTOBS_REPLACE(IFILT_OBS) .NE. IFILT_OBS) GOTO 222

            VARNAME   = 'PKMJD_FIT_' // cfilt(1:1) // ':F'
            CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PKMJD_FIT(ifilt_obs),
     &           VARNAME(1:20)//char(0), 1, LENBLOCK, 20 )

            VARNAME   = 'PKMJD_ERR_' // cfilt(1:1) //  ':F'
            CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PKMJD_ERR(ifilt_obs),
     &           VARNAME(1:20)//char(0), 1, LENBLOCK, 20 )

 222     CONTINUE

c --------------------------
c      fit chi2 per filter
          CALL TABLE_VARLIST_FILTERS('FIT_CHI2','F', ADDCOL_FILTERS,
     &           VARLIST, LENLIST )
          CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_CHI2_FITPKMJD(1),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)

c --------------------------
c      fit NDOF per filter
          CALL TABLE_VARLIST_FILTERS('FIT_NDOF','I', SURVEY_FILTERS,
     &           VARLIST, LENLIST)
          CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NDOF_FITPKMJD(1),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)

      ENDIF  ! end of SETPKMJD if-block

c - - - - - -
      IF ( LPROB_TRUEFLUX .and. ISJOB_SIM ) THEN

c global PROB_TRUEFLUX for all bands combined
        VARNAME   = 'PROB_TRUEFLUX:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PROB_TRUEFLUX(0),
     &        VARNAME(1:20), 1, LENBLOCK, 20)

c ... and for each individual band
        CALL TABLE_VARLIST_FILTERS('PROB_TRUEFLUX','F', ADDCOL_FILTERS,
     &         VARLIST, LENLIST )
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_PROB_TRUEFLUX(1),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)

        CALL TABLE_VARLIST_FILTERS('NDOF_TRUEFLUX','I', ADDCOL_FILTERS,
     &         VARLIST, LENLIST )
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ADDCOL_NDOF_TRUEFLUX(1),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)

      ENDIF

c - - - - -  min and max MJD
      VARLIST = 'MJDMIN:D,MJDMAX:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, SNLC8_MJDMIN,
     &                VARLIST, 0,   LENBLOCK, 20 )

c - - - - - MJD_DETECT and MJD_TRIGGER (Sep 2023) - - - - -

      VARLIST = 'MJD_TRIGGER:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, SNLC8_MJD_TRIGGER,
     &                VARLIST, 0,   LENBLOCK, 20 )

      VARLIST = 'MJD_DETECT_FIRST:D,MJD_DETECT_LAST:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, SNLC8_MJD_DETECT_FIRST,
     &                VARLIST, 0,   LENBLOCK, 20 )


c - - - -  multi-season variability - - - -
      IF( MULTISEASON_OPTMASK > 0 ) THEN

c Aug 15 2018: include NTOT and NLC in output and TEXT output
        VARLIST = 'NSEASON_TOT:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NSEASON_TOT, VARLIST,1,
     &                   LENBLOCK, 40 )

        VARLIST = 'NSEASON_ACTIVE:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NSEASON_ACTIVE, VARLIST,1,
     &                   LENBLOCK, 40 )

        VARLIST = 'MULTISEASON_CHI2RED_1:F,' //
     &            'MULTISEASON_CHI2RED_2:F,' //
     &            'MULTISEASON_CHI2RED_3:F,' //
     &            'MULTISEASON_CHI2RED_4:F,' //
     &            'MULTISEASON_CHI2RED_5:F'  //
     &          char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, MULTISEASON_CHI2RED(1),
     &               VARLIST,0,     LENBLOCK, 160 )

        VARLIST = 'MULTISEASON_AVGFLUX_1:F,' //
     &            'MULTISEASON_AVGFLUX_2:F,' //
     &            'MULTISEASON_AVGFLUX_3:F,' //
     &            'MULTISEASON_AVGFLUX_4:F,' //
     &            'MULTISEASON_AVGFLUX_5:F' //
     &          char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, MULTISEASON_AVGFLUX(1),
     &              VARLIST,0,       LENBLOCK, 160 )
      ENDIF

c ------------------------------------


      IF ( IFLAG .EQ. 1 ) THEN

c snana variables with no fitting.

         VARLIST = 'TrestMIN:F,TrestMAX:F,TrestRange:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_TRESTMIN,
     &               VARLIST, 0,     LENBLOCK, 40 )

         VARLIST = 'TobsMIN:F,TobsMAX:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_TOBSMIN,
     &               VARLIST, 0,    LENBLOCK,  40 )

         VARLIST = 'TGAPMAX:F,T0GAPMAX:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_TGAPMAX,
     &                VARLIST, 0,   LENBLOCK, 40 )

         VARLIST =
     &      'NFILT_Tmin:I,NFILT_Tmax:I,NFILT_Trest2:I' // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK,ISNLC_NFILT_TRESTMIN,
     &              VARLIST,0,     LENBLOCK, 40 )

         VARLIST = 'NFILT_SNRMAX:I,NFILT_SNRMAX2:I'  // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ISNLC_NFILT_SNRMAX,
     &                VARLIST,0,    LENBLOCK, 40 )

         VARLIST = 'SNRMAX:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_SNRMAX_SORT(1),
     &                VARLIST,0,   LENBLOCK, 20 )

         VARLIST = 'SNRMAX1:F,SNRMAX2:F,SNRMAX3:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNLC_SNRMAX_SORT(1),
     &               VARLIST,1,    LENBLOCK, 40 )

c ----------
c Below are SNANA variables for which the FIT analog is not
c available here -> book FIT-analogs in snlc_fit.car

         CALL TABLE_VARLIST_FILTERS('SNRMAX', 'F', ADDCOL_FILTERS,
     &                    VARLIST, LENLIST )
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_SNRMAX(1),
     &      VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)

         CALL TABLE_VARLIST_FILTERS('XTMW', 'F', ADDCOL_FILTERS,
     &                    VARLIST, LENLIST )
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_XTMW(1),
     &      VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)

      ELSE

c variables re-evaluated after fit

         VARLIST = 'TrestMIN:F,TrestMAX:F,TrestRange:F'  // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TRESTMIN_FIT,
     &                 VARLIST, 0,  LENBLOCK, 40 )

         VARLIST = 'TobsMIN:F,TobsMAX:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TOBSMIN_FIT,
     &                  VARLIST, 0, LENBLOCK, 40 )

         VARLIST = 'TGAPMAX:F,T0GAPMAX:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TGAPMAX_FIT,
     &                 VARLIST, 0,  LENBLOCK, 40 )

         VARLIST = 'NFILT_Tmin:I,NFILT_Tmax:I' // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NFILT_TRESTMIN_FIT,
     &                VARLIST,0,   LENBLOCK, 40 )


         VARLIST = 'NFILT_SNRMAX:I,NFILT_SNRMAX2:I' // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NFILT_SNRMAX_FIT,
     &                 VARLIST,0,  LENBLOCK, 40 )

         VARLIST = 'SNRMAX:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNRMAX_SORT_FIT(1),
     &                VARLIST,0,    LENBLOCK, 20 )

         VARLIST = 'SNRMAX1:F,SNRMAX2:F,SNRMAX3:F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNRMAX_SORT_FIT(1),
     &                 VARLIST,1,  LENBLOCK, 40 )

      ENDIF


c - - - - - -  nearest nbr (Apr 2014) - - - - -
      LTMP = ( IFLAG .EQ. 2 )     .and.
     &       ( NVAR_NEARNBR > 0 ) .and.
     &       ( FLAG_NEARNBR .EQ. NNFLAG_APPLY )
      LTMP = LTMP .or.
     &       (IFLAG.EQ.2 .and. NN_ITYPE_FIX .GE. 0 )  ! Jan 18 2016

      IF ( LTMP ) THEN
         VARLIST = 'NN_ITYPE:I' // char(0)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NN_ITYPE, VARLIST,1,
     &                   LENBLOCK, 20 )

         VARLIST = 'NN_NCELL:I' // char(0)   ! with training cuts (no NN)
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NN_NCELL, VARLIST,0,
     &                   LENBLOCK, 20 )

         VARLIST = 'NN_PROB_IA:F' // char(0)  ! Bayesian prob with NN cut
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, NN_PROB_IA, VARLIST, 1,
     &                   LENBLOCK, 20)

      ENDIF

c - - - - - - private vars - - - - -

c for PRIVATE variables in data files,
c glue together variables in comma-separate VARLIST

      IF ( NVAR_PRIVATE .GT. 0 ) THEN
           CTMP    = PRIVATE_VARNAME(1)(1:MXCHAR_FILEWORD-1) // ' '
           LENNAME = INDEX(CTMP,' ') - 1
           VARLIST = CTMP(1:LENNAME) // ':D'
        do ivar = 2, NVAR_PRIVATE
           CTMP    = PRIVATE_VARNAME(ivar)
           LENNAME = INDEX(CTMP,' ') - 1
           LENLIST = INDEX(VARLIST,' ') - 1
           VARLIST = VARLIST(1:LENLIST) // ',' //
     &        CTMP(1:LENNAME) // ':D'

        enddo

        LENLIST = INDEX(VARLIST,' ') - 1
        VARLIST = VARLIST(1:LENLIST) // char(0)

        CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, PRIVATE_VALUE(1),
     &                VARLIST, 0,   LENBLOCK, LENLIST)
      ENDIF     ! end of NPAR_PRIVATE if-block

c --- Sep 23 2017: user variables --------
      IF ( NTABLEVAR_USER > 0 ) THEN
        DO ivar = 1, NTABLEVAR_USER
          VARLIST = TABLEVARNAME_USER(ivar)
          LENLIST = INDEX(VARLIST,' ') - 1
          VARLIST = VARLIST(1:LENLIST) // ':F' // char(0)
          CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TABLEVALUE_USER(1),
     &               VARLIST, 1, LENBLOCK, LENLIST+2)
        ENDDO
      ENDIF

      RETURN
      END   !  end of INIT_TABLE_SNANAVAR


C ======================================
CDECK  ID>,  INIT_TBHOSTVAR. 
      SUBROUTINE INIT_TABLE_HOSTVAR(ID, IGAL, ITEXT, BLOCK)

c Created Sep 2023
c init table column for HOST_XXX (igal=1) or HOST2_XXX (igal=2)
c
c  Inputs
c   ID   : table ID
c   IGAL : 1 for best match, >1 for other matches
c   ITEXT: 1 -> write to text also
c
c
c Feb 23 2024: pass ITEXT for HOST MAGS so that they appear with
c              SNTABLE_LIST = 'SNANA(text:key,text:host)'
c
      IMPLICIT NONE

c subroutine args
      INTEGER ID, IGAL, ITEXT   ! (I)
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)

c local var
      CHARACTER PREFIX*8, VARLIST*400, CBLOCK*40
      INTEGER   LP, LENLIST, LENBLOCK, ITEXT_LOCAL


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c ------------- BEGIN ----------

      if ( IGAL == 1 ) then
        PREFIX = 'HOST_'
        LP     = 5
      else
        write(PREFIX,20) IGAL
        LP = 6
20      format('HOST',I1,'_')
      endif

      LENBLOCK     = INDEX(BLOCK//' ',' ') - 1
      CBLOCK       = BLOCK(1:LENBLOCK) // char(0)
      LENLIST      = LEN(VARLIST)

c store HOST_OBJID as double precision because
c  * root tree supports Long64_t, but does not read back correctly
c  * hbook cwnt does not support long long int.
c  * sntable_dump extraction will write real*8 as integer.

      VARLIST =  PREFIX(1:LP) // 'OBJID:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, DSNHOST_OBJID(1),
     &             VARLIST,ITEXT,     LENBLOCK, 20 )

      VARLIST =  PREFIX(1:LP) // 'ZPHOT:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_ZPHOT(1),
     &             VARLIST,ITEXT,    LENBLOCK, 40 )
      VARLIST =  PREFIX(1:LP) // 'ZPHOTERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_ZPHOT_ERR(1),
     &               VARLIST,ITEXT,    LENBLOCK, 40 )

      VARLIST =  PREFIX(1:LP) // 'ZSPEC:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_ZSPEC(1),
     &             VARLIST,ITEXT,    LENBLOCK, 40 )
      VARLIST =  PREFIX(1:LP) // 'ZSPECERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_ZSPEC_ERR(1),
     &              VARLIST,ITEXT,  LENBLOCK, 40 )

      VARLIST = PREFIX(1:LP) // 'RA:D'  // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, SNHOST8_RA(1),
     &          VARLIST,ITEXT,    LENBLOCK, 20 )
      VARLIST = PREFIX(1:LP) // 'DEC:D'  // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, SNHOST8_DEC(1),
     &          VARLIST,ITEXT,   LENBLOCK, 20 )

      VARLIST = PREFIX(1:LP) // 'ANGSEP:F'  // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_ANGSEP(1),
     &         VARLIST,ITEXT,   LENBLOCK, 20 )

      VARLIST = PREFIX(1:LP) // 'DDLR:F'  // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_DDLR(1),
     &          VARLIST,ITEXT,    LENBLOCK, 20 )

      if ( igal == 1 ) then
        VARLIST = 'HOST_CONFUSION:F'  // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_CONFUSION,
     &          VARLIST,ITEXT,    LENBLOCK, 20 )
      endif

c physical properties
      ITEXT_LOCAL = 1  ! always write properties to text format
      if ( IGAL > 1 ) ITEXT_LOCAL = ITEXT  ! optional for other host matches

      IF ( EXIST_SNHOST_LOGMASS ) THEN
        VARLIST =  PREFIX(1:LP) // 'LOGMASS:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_LOGMASS(1),
     &          VARLIST, ITEXT_LOCAL,    LENBLOCK, 40 )
        VARLIST =  PREFIX(1:LP) // 'LOGMASS_ERR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_LOGMASS_ERR(1),
     &          VARLIST, ITEXT_LOCAL,     LENBLOCK, 40 )
      ENDIF

      IF ( EXIST_SNHOST_LOGSFR ) THEN
        VARLIST =  PREFIX(1:LP) // 'LOGSFR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_LOGSFR(1),
     &            VARLIST, ITEXT_LOCAL,    LENBLOCK, 40 )
        VARLIST =  PREFIX(1:LP) // 'LOGSFR_ERR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_LOGSFR_ERR(1),
     &            VARLIST, ITEXT_LOCAL,    LENBLOCK, 40 )
      ENDIF

      IF ( EXIST_SNHOST_LOGsSFR ) THEN
        VARLIST =  PREFIX(1:LP) // 'LOGsSFR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_LOGsSFR(1),
     &            VARLIST, ITEXT_LOCAL,   LENBLOCK, 40 )
        VARLIST =  PREFIX(1:LP) // 'LOGsSFR_ERR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_LOGsSFR_ERR(1),
     &           VARLIST, ITEXT_LOCAL,    LENBLOCK, 40 )
      ENDIF

      IF ( EXIST_SNHOST_COLOR ) THEN
        VARLIST =  PREFIX(1:LP) // 'COLOR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_COLOR(1),
     &             VARLIST, ITEXT_LOCAL,    LENBLOCK, 40 )
        VARLIST =  PREFIX(1:LP) // 'COLOR_ERR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SNHOST_COLOR_ERR(1),
     &           VARLIST, ITEXT_LOCAL,     LENBLOCK, 40 )
      ENDIF

      IF ( EXIST_SNHOST_MAGOBS .and. IGAL == 1 ) THEN    ! host mags
        CALL TABLE_VARLIST_FILTERS('HOST_MAG', 'F', ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, ADDCOL_SNHOST_MAGOBS(1,1),
     &      VARLIST(1:LENLIST)//char(0), ITEXT, LENBLOCK, LENLIST)
      ENDIF

      RETURN
      END    ! INIT_TABLE_HOSTVAR

C =============================================
CDECK  ID>,  TBOBSVAR. 
      SUBROUTINE INIT_TABLE_SNOBSVAR(ID, BLOCK)

c Mar 2 2015:
c Book epoch info in SNANA table.
c
c Sep 23 2017: reduce MXOBS down to 1000 so that MJD*8 is handled by hbook.
c Oct 16 2017: include CCDNUM if it is there.
c Mar 03 2018: include SIM_FLUXCAL_HOSTERR(NOBS):F
c Mar 18 2018: include DTOBS(NOBS):F and DTOBS_SAMEFILT(NOBS):F
c
c Nov 30 2020:
c    + change a few VARNAMEs to match names in FITRES+RESIDUALS
c    + add CHI2FLUX_SIM
c    + add several variables: GAIN, SKYSIG_T ...
c    + remove a few obscure variables
c       (DTOBSLAST, DTOBSLAST_SAMEFILT, FLUXCAL_HOSTERRCALC)
c - - - - - - - - -

      IMPLICIT NONE

      INTEGER   ID          ! (I) table id
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)

      INTEGER MXOBS_SNTABLE
      PARAMETER (MXOBS_SNTABLE = 900) ! cannot exceed 1000 for MJD*8

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      INTEGER LENV, LENB, LENTMP
      CHARACTER CBLK*40, CNOBS*14, VARNAME*40
      LOGICAL  IGNORE

      EXTERNAL
     &    SNTABLE_ADDCOL
     &   ,SNTABLE_ADDCOL_int
     &   ,SNTABLE_ADDCOL_flt
     &   ,SNTABLE_ADDCOL_dbl
     &   ,SNTABLE_ADDCOL_str
      LOGICAL  IGNOREFILE_fortran

C --------------- BEGIN -------------

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5)
      call flush(6)

      LENV   = LEN(VARNAME)
      LENB   = INDEX(BLOCK//' ',' ') - 1
      CBLK   = BLOCK(1:LENB) // char(0)

      write(CNOBS,15) MXOBS_SNTABLE
15    format('NOBS[',I4.4,']' )  ! no spaces or commas in string
      VARNAME = CNOBS(1:12)  // char(0)  ! Nobs used in fit + NREJECT
      CALL SNTABLE_ADDCOL_int(ID, CBLK, ISNLC_NEWMJD_STORE,
     &     VARNAME, 0, LENB, LENV)

      VARNAME = 'USEFLAG(NOBS):I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID,CBLK, ISNLC_SNRECON_USE(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'PHOTFLAG(NOBS):I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID,CBLK, ISNLC_PHOTFLAG(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'PHOTPROB(NOBS):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_PHOTPROB(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'IFILTOBS(NOBS):I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID,CBLK, ISNLC_IFILT_OBS(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'MJD(NOBS):D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID,CBLK, SNLC8_MJD(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXCAL_DATA(NOBS):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_FLUXCAL(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXCAL_DATA_ERR(NOBS):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_FLUXCAL_ERRTOT(1),
     &      VARNAME, 0, LENB,LENV)

c -- observing conditions

      VARNAME = 'ZP(NOBS):F' // char(0)    ! match FITRES+RESID table
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_ZEROPT(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'ZP_ERR(NOBS):F' // char(0)    ! match FITRES+RESIDS table
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_ZEROPT_ERR(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'PSF(NOBS):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_PSF_SIG1(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'SKYSIG(NOBS):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_SKYSIG(1),
     &      VARNAME, 0, LENB,LENV)
      VARNAME = 'SKYSIG_T(NOBS):F' // char(0)    ! Nov 30 2020
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_SKYSIG_T(1),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'GAIN(NOBS):F' // char(0)    ! Nov 30 2020
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_GAIN(1),
     &      VARNAME, 0, LENB,LENV)

c --- error calculated from PSF+SKY+ZP, as the simulation would do

      VARNAME = 'FLUXCAL_ERRCALC(NOBS):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SNLC_FLUXCAL_ERRCALC(1),
     &      VARNAME, 0, LENB,LENV)

c - - - - - - - - - - - - - - - -

      IF ( ISJOB_SIM ) THEN
         VARNAME = 'FLUXCAL_SIM(NOBS):F' // char(0)   ! match FITRES+RESIDS
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, SIM_EPFLUXCAL(1),
     &        VARNAME, 0, LENB,LENV)

         VARNAME = 'CHI2FLUX_SIM(NOBS):F' // char(0)  ! match FITRES+RESIDS
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, SIM_EPCHI2FLUX(1),
     &        VARNAME, 0, LENB,LENV)

         VARNAME = 'MAGOBS_SIM(NOBS):F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, SIM_EPMAGOBS(1),
     &        VARNAME, 0, LENB,LENV)
      ENDIF

      IF ( LSIM_SNANA ) THEN
         VARNAME = 'SIM_FLUXCAL_HOSTERR(NOBS):F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, SIM_EPFLUXCAL_HOSTERR(1),
     &        VARNAME, 0, LENB,LENV)
      ENDIF

c include SNR_MAG[mag] if it exists.
      LENTMP  = INDEX(SIMNAME_SNRMON,' ')-1
      IGNORE  = ( IGNOREFILE_fortran(SIMNAME_SNRMON) )
      IF ( LSIM_SNANA .and. (.not.IGNORE)  ) THEN
         VARNAME = SIMNAME_SNRMON(1:LENTMP)// '(NOBS):F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, SIM_EPSNRMON(1),
     &        VARNAME, 0, LENB,LENV)
      ENDIF

      RETURN
      END   ! end INIT_TABLE_SNOBSVAR


C =============================================
CDECK  ID>,  INIT_TABLE_SIM_MAGOBS. 
      SUBROUTINE INIT_TABLE_SIM_MAGOBS(ID, BLOCK)

c Feb 2019
c Book only MODEL-MAG vs. EPOCH (much smaller output than SNANA+EPOCHS)
c MODEL-MAG is interpolated on a grid to enable plotting model colors.
c
c  NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS

      IMPLICIT NONE

      INTEGER   ID          ! (I) table id
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER LENV, LENB, IFILT, IFILT_OBS
      LOGICAL IGNORE
      CHARACTER CBLK*40, CNOBS*20, VARNAME*40, cfilt*2

      EXTERNAL
     &    SNTABLE_ADDCOL
     &   ,SNTABLE_ADDCOL_int
     &   ,SNTABLE_ADDCOL_flt
     &   ,SNTABLE_ADDCOL_dbl
     &   ,SNTABLE_ADDCOL_str

C --------------- BEGIN -------------

      IF ( .not. LSIM_SNANA ) RETURN ! sim only

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5)
      call flush(6)

      LENV   = LEN(VARNAME)
      LENB   = INDEX(BLOCK//' ',' ') - 1
      CBLK   = BLOCK(1:LENB) // char(0)

      write(CNOBS,15) MXEP_MODELGRID
15    format('NEP_MODEL[',I4.4,']' )  ! no spaces or commas in string
      VARNAME = CNOBS(1:15)  // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLK, NEP_SIM_MODELGRID,
     &     VARNAME, 0, LENB, LENV)

      VARNAME = 'EPOCH_MODEL(NEP_MODEL):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, SIM_MODELGRID_TOBS(1),
     &      VARNAME, 0, LENB,LENV)

      DO ifilt = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
          VARNAME   = 'MAGOBS_MODEL_' // cfilt(1:1) //
     &                    '(NEP_MODEL):F' // char(0)
          CALL SNTABLE_ADDCOL_flt(ID,CBLK,
     &          SIM_MODELGRID_MAGOBS(1,ifilt),
     &          VARNAME, 0, LENB,LENV )
      ENDDO

      RETURN
      END   ! end INIT_TABLE_SIM_MAGOBS

C =============================================
CDECK  ID>,  FILL_TABLE_SIM_MAGOBS. 
      SUBROUTINE LOAD_TABLE_SIM_MAGOBS()

c Feb 2019:
c   load SIM_MODELGRID arrays for MODELMAG table.
c   This CWNT is designed to enable plotting model color vs. epoch
c
c NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS

      IMPLICIT NONE

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IGRID, NEP, IFILT, IFILT_OBS
      REAL MAGOBS, TOBS

c function
      REAL SIM_MAGOBS_INTERP

C ---------- BEGIN ----------

      IF ( .not. LSIM_SNANA ) RETURN ! sim only

c define arbitrary epoch grid

      NEP = 0
      DO IGRID = -40, 100, 2
         NEP  = NEP + 1
         TOBS = FLOAT(IGRID)
         SIM_MODELGRID_TOBS(NEP) = TOBS

         DO ifilt = 1, NFILTDEF_SURVEY
            MAGOBS = SIM_MAGOBS_INTERP(ifilt,TOBS)
            SIM_MODELGRID_MAGOBS(NEP,IFILT) = MAGOBS
         ENDDO
      ENDDO
      NEP_SIM_MODELGRID = NEP
      RETURN
      END

CDECK  ID>,  SIM_MAGOBS_INTERP. 
      REAL FUNCTION SIM_MAGOBS_INTERP(IFILT,Tobs)

C Return interpolated SIM_MAGOBS for inputs:
c   * IFILT  = sparse filter index
c   * Tobs   = MJD - SIM_PEAKMJD

      IMPLICIT NONE

      INTEGER IFILT
      REAL Tobs


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER NEWMJD, EP, EPMIN, EPMAX, IFILT_OBS, EP0, EP1
      REAL MAGOBS, Tobs_tmp, T0, T1, MAG0, MAG1, frac
      REAL*8 MJD8
C ------------ BEGIN -----------

      MAGOBS = 99.0  ! init value

      T0=-9999. ; T1=-9999. ; EP0 = -9; EP1 = -9
      DO 100 NEWMJD = 1, ISNLC_NEWMJD_STORE
        EPMIN  = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX  = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        DO 101 EP = EPMIN, EPMAX
            IFILT_OBS = ISNLC_IFILT_OBS(ep)
            IF ( IFILT .NE. IFILTDEF_INVMAP_SURVEY(ifilt_obs)) GOTO 101
            MJD8      = SNLC8_MJD(EP)
            Tobs_tmp  = sngl(MJD8) - SIM_PEAKMJD
            MAGOBS    = SIM_EPMAGOBS(ep)
            if ( Tobs_tmp < Tobs ) then
               EP0 = EP; T0 = Tobs_tmp; MAG0 = MAGOBS
            endif
            if ( Tobs_tmp > Tobs .and. T1 < -999. ) THEN
               EP1 = ep; T1 = Tobs_tmp ; MAG1 = MAGOBS ; goto 444
            endif
 101     CONTINUE
 100  CONTINUE

 444  CONTINUE

      IF ( EP0 > 0 .and. EP1 > 0 ) THEN
         FRAC   = (Tobs-T0)/(T1-T0)
         MAGOBS = MAG0 + (MAG1-MAG0) * frac
      ENDIF

      SIM_MAGOBS_INTERP = MAGOBS

      RETURN
      END

C ========================================
CDECK  ID>,  TBSIMVAR. 
      SUBROUTINE INIT_TABLE_SIMVAR(ID,BLOCK)

c Created Feb 02, 2013
c Initialize table for simulated variables.
c
c Feb 27, 2020: add SIM_HOSTLIB_GALID
c Mar 19, 2020: add SIM_RV  to table
c Sep 11, 2020: add PySEDMODEL = BYOSED or SNEMO
c Dec 28, 2020: write SIM_gammaDM to TEXT file if non-zero
c Dec     2022: remove SIM_TYPE_INDEX
c Jan  8  2023: restore SIM_TYPE_INDEX (forgot why it was removed)
c Dec 23  2023: add SIM_WGT_POPULATION
c
      IMPLICIT  NONE
      INTEGER   ID          ! (I) table id
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      CHARACTER
     &    CTMP*(MXCHAR_FILEWORD)
     &  , VARLIST*400, CBLOCK*40
      INTEGER LENLIST, IPAR, LENBLOCK, LENTMP, LENM, ITEXT

      EXTERNAL
     &    SNTABLE_ADDCOL
     &   ,SNTABLE_ADDCOL_int
     &   ,SNTABLE_ADDCOL_flt
     &   ,SNTABLE_ADDCOL_dbl
     &   ,SNTABLE_ADDCOL_str

C ---------------- BEGIN ---------------

      IF ( .NOT. LSIM_SNANA         ) RETURN
      IF ( .NOT. WRTABLEFILE_SIMVAR ) RETURN


      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5)
      call flush(6)

      LENBLOCK = INDEX(BLOCK//' ',' ') - 1
      LENLIST  = LEN(VARLIST)
      CBLOCK   = BLOCK(1:LENBLOCK) // char(0)


      IF ( SIM_SUBSAMPLE_INDEX >= 0 ) THEN
        VARLIST = 'SIM_SUBSAMPLE_INDEX:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID,CBLOCK,SIM_SUBSAMPLE_INDEX,
     &                VARLIST, 0,     LENBLOCK, LENLIST)
      ENDIF

      VARLIST = 'SIM_TYPE_INDEX:I' //char(0)
      CALL SNTABLE_ADDCOL(ID, CBLOCK, SIM_GENTYPE,  VARLIST, 1,  ! legacy name
     &                   LENBLOCK, LENLIST)

      VARLIST = 'SIM_TEMPLATE_INDEX:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SIM_TEMPLATE_INDEX,
     &               VARLIST,1,    LENBLOCK, LENLIST)

c Mar 22 2016: always output SIM_LIBID
cc      IF ( BTEST(SIMLIB_MSKOPT,1) ) THEN
        VARLIST = 'SIM_LIBID:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SIM_LIBID,  VARLIST, 1,
     &                   LENBLOCK, LENLIST)
        VARLIST = 'SIM_NGEN_LIBID:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SIM_NGEN_LIBID,  VARLIST, 1,
     &                   LENBLOCK, LENLIST)
cc      ENDIF

      VARLIST = 'SIM_NOBS_UNDEFINED:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SIM_NOBS_UNDEFINED,
     &            VARLIST,0,       LENBLOCK, LENLIST)

      VARLIST = 'SIM_SEARCHEFF_MASK:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SIM_SEARCHEFF_MASK,
     &               VARLIST, 0,    LENBLOCK, LENLIST)

      VARLIST = 'SIM_MAGSMEAR_COH:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_MAGSMEAR_COH,
     &             VARLIST, 0,      LENBLOCK, LENLIST)

      VARLIST = 'SIM_MWEBV:F' // char(0)  ! added Nov 26 2016
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_MWEBV,
     &                VARLIST, 0,   LENBLOCK, LENLIST)

      VARLIST = 'SIM_ZCMB:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_REDSHIFT_CMB,
     &              VARLIST, 1,     LENBLOCK, LENLIST)

      VARLIST = 'SIM_ZHELIO:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_REDSHIFT_HELIO,
     &                VARLIST, 0,    LENBLOCK, LENLIST)

      VARLIST = 'SIM_ZHOST:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_REDSHIFT_HOST,
     &             VARLIST, 0,      LENBLOCK, LENLIST)

      VARLIST = 'SIM_ZFLAG:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, SIM_REDSHIFT_FLAG,
     &              VARLIST, 1,     LENBLOCK, LENLIST)

      VARLIST = 'SIM_VPEC:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_VPEC,
     &               VARLIST, 1,    LENBLOCK, LENLIST)

      VARLIST = 'SIM_DLMAG:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_DLMAG,
     &               VARLIST, 1,    LENBLOCK, LENLIST)

      VARLIST = 'SIM_LENSDMU:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_LENSDMU,
     &               VARLIST, 0,    LENBLOCK, LENLIST)

      VARLIST = 'SIM_PEAKMJD:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_PEAKMJD,
     &               VARLIST, 1,     LENBLOCK, LENLIST)

      if ( SIM_MJD_EXPLODE > 0.0 ) then
        VARLIST = 'SIM_MJD_EXPLODE:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_MJD_EXPLODE,
     &                VARLIST, 1,    LENBLOCK, LENLIST)
      endif

c - -
      VARLIST = 'SIM_WGT_POP' // ':F'   // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_WGT_POPULATION,
     &               VARLIST, 1,     LENBLOCK, LENLIST)

      LENTMP = INDEX(SIMNAME_SHAPEPAR,' ') - 1  ! x1, delta, dm15
      VARLIST = SIMNAME_SHAPEPAR(1:LENTMP) // ':F'   // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_SHAPEPAR,
     &               VARLIST, 1,     LENBLOCK, LENLIST)

      LENTMP = INDEX(SIMNAME_COLORPAR,' ') - 1  ! c, AV
      VARLIST = SIMNAME_COLORPAR(1:LENTMP) // ':F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_COLORPAR,
     &              VARLIST, 1,     LENBLOCK, LENLIST)

      LENTMP = INDEX(SIMNAME_SHAPELAW,' ') - 1   ! SIM_alpha
      VARLIST = SIMNAME_SHAPELAW(1:LENTMP) // ':F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_SHAPELAW,
     &              VARLIST, 1,     LENBLOCK, LENLIST)

      LENTMP = INDEX(SIMNAME_COLORLAW,' ') - 1   ! SIM_beta
      VARLIST = SIMNAME_COLORLAW(1:LENTMP) // ':F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_COLORLAW,
     &                VARLIST, 1,   LENBLOCK, LENLIST)

c add SIM_gammaDM if not zero.
c Sep 7 2021: always write SIM_gammaDM in case first value is 0
c    followed by non0-zero values.
      VARLIST = 'SIM_gammaDM:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_SALT2gammaDM,
     &                VARLIST, 1,   LENBLOCK, LENLIST )

      VARLIST = 'SIM_x0:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_SALT2x0,
     &                VARLIST, 1,   LENBLOCK, LENLIST)

      VARLIST = 'SIM_mB:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_SALT2mb,
     &                VARLIST, 1,   LENBLOCK, LENLIST)

c add SIM_AV only if not already defined.
c This is for the SALT2 model with intinsic color (c) and
c external scatter (SIM_AV) from dust.
c Aug 2 2022: perform test only for SALT2 model.

      if ( SIM_MODEL_INDEX .EQ. MODEL_SALT2 ) then
        if ( SIMNAME_COLORPAR(1:6) .NE. 'SIM_AV' ) then
          VARLIST = 'SIM_AV:F' // char(0)
          CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_AV,
     &               VARLIST, 1,    LENBLOCK, LENLIST)
          VARLIST = 'SIM_RV:F' // char(0)
          CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_RV,
     &                VARLIST, 1,     LENBLOCK, LENLIST)
        endif
      endif

c  SIMSED model params; glue SIMSED_ prefix (Feb 2014)
c  Apr 28 2015: set DOTEXT flag to 1

      DO IPAR    = 1, NPAR_SIMSED
         CTMP    = SIMSED_PARNAME(ipar)
         LENTMP  = INDEX(CTMP,' ') - 1
         VARLIST = 'SIMSED_' // CTMP(1:LENTMP) // ':F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, SIMSED_PARVAL(ipar),
     &        VARLIST, 1, LENBLOCK, LENLIST)
      ENDDO


c PySEDMODEL model params (BYOSED, SNEMO, ...)
      DO IPAR    = 1, NPAR_PySEDMODEL
         LENM    = INDEX(PySEDMODEL_NAME,' ') - 1
         CTMP    = PySEDMODEL_PARNAME(ipar)
         LENTMP  = INDEX(CTMP,' ') - 1
         VARLIST = PySEDMODEL_NAME(1:LENM) // '_'
     &             // CTMP(1:LENTMP) // ':F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, PySEDMODEL_PARVAL(ipar),
     &        VARLIST, 1, LENBLOCK, LENLIST)
      ENDDO

c Feb 2018: LCLIB model params
      IF ( SIM_MODEL_INDEX == MODEL_LCLIB ) THEN
        CALL TABLE_VARLIST_FILTERS('SIM_TEMPLATEMAG','F',ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, SIM_TEMPLATEMAG(1),
     &          VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)

        DO IPAR    = 1, NPAR_LCLIB
           CTMP    = LCLIB_PARNAME(ipar)
           LENTMP  = INDEX(CTMP,' ') - 1
           VARLIST = 'LCLIB_' // CTMP(1:LENTMP) // ':F' // char(0)
           CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, LCLIB_PARVAL(ipar),
     &            VARLIST,1,   LENBLOCK, LENLIST)
        ENDDO
      ENDIF

c SIM_HOSTLIB params

      ITEXT = 0
      if ( WRTABLEFILE_HOST_TEXT ) ITEXT=1
      VARLIST = 'SIM_HOSTLIB_GALID' // ':D' // char(0) ! Feb 2020
         CALL SNTABLE_ADDCOL_dbl(ID,CBLOCK, DSIM_HOSTLIB_GALID,
     &        VARLIST, ITEXT,    LENBLOCK, LENLIST)

      DO IPAR    = 1, NPAR_SIM_HOSTLIB
         CTMP    = SIM_HOSTLIB_PARNAME(ipar)
         LENTMP  = INDEX(CTMP,' ') - 1
         VARLIST = 'SIM_HOSTLIB_' // CTMP(1:LENTMP) // ':F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, SIM_HOSTLIB_PARVAL(ipar),
     &        VARLIST, ITEXT,    LENBLOCK, LENLIST)
      ENDDO

c - - - - - optional LCWIDTH for simulated MAGOBS -----
      if ( OPTSIM_LCWIDTH > 0 ) then
        CALL TABLE_VARLIST_FILTERS('SIM_LCWIDTH','F', ADDCOL_FILTERS,
     &           VARLIST, LENLIST)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, SIM_LCWIDTH(1),
     &      VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)
      endif

      RETURN
      END    ! end of INIT_TABLE_SIMVAR


C ===========================
CDECK  ID>,  TBCIDPTR. 
      SUBROUTINE TABLE_CIDPTR(IFLAG)
c
c Created Feb 2013
c
c Replacement for obsolete function HFCIDPTR.
c Plot list of CIDs with light curve plots.
c Fits that fail have CID=-9.
c Used by the lc-plotting tool
c
c Sep 22 2020: fix swapped args in SNTABLE_CREATE
c ----------------------------------------------------

      IMPLICIT NONE

      INTEGER IFLAG  ! (I) see IFLAG_XXX params


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER   ID, CID, IPLOT
      INTEGER   LENNAME, LENBLOCK, LENLIST
      CHARACTER CNAME*20, CBLOCK*20, VARLIST*20, TEXTFMT*4

      COMMON / IPLOTCOM / CID, IPLOT
c function
      INTEGER IPLOT_JOBSPLIT
      EXTERNAL SNTABLE_ADDCOL, SNTABLE_ADDCOL_int

C ------------ BEGIN ------------

      ID    = IDTABLE_CIDPTR

      IF ( IFLAG .EQ. IFLAG_INI ) THEN
        CNAME    = 'CIDPTR' // char(0)
        LENNAME  = INDEX(CNAME,' ') - 1
        TEXTFMT  = ' ' // char(0)  ! never make a text table
        CALL SNTABLE_CREATE(ID, CNAME, TEXTFMT, LENNAME, 1 )  ! C function

        CBLOCK = 'IPLOT' // char(0)
        LENBLOCK = INDEX(CBLOCK,' ') - 1
        LENLIST  = LEN(VARLIST)
        VARLIST = 'CID:I,IPLOT:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, CID,
     &        VARLIST, 0, LENBLOCK,LENLIST)

        RETURN
      ENDIF

c --------------------------
c fill table.

      IPLOT = IPLOT_JOBSPLIT(N_SNLC_PLOT)
      CID   = SNLC_CID
      CALL SNTABLE_FILL(ID)  ! generic C function

      RETURN
      END   ! end TABLE_CIDPTR


C ===================================================
CDECK  ID>,  TBVFILT. 
      SUBROUTINE TABLE_VARLIST_FILTERS(PREFIX,CAST,FILTERS,
     &            VARLIST,LENLIST)

c Created Sep 28, 2012
c
c For input PREFIX  and defined FILTERS,  return
c comma-separate list of variable names for column-wise ntuple.
c Example for FILTERS=gri,
c
c VARLIST = '[PREFIX]_g,[PREFIX]_r,[PREFIX]_i'
c
c If a filter is case-insensitive duplicate (i.e., u & U)
c then append '2' at the end of the variable name.
c The returned VARLIST is used in the HBNAME calls,
c and hence case-insensitive duplicates must be distiguished
c for ntuples.
c
c Feb  1, 2013: include ':F' after each variable.
c Feb  5, 2013: return LENLIST
c Feb 15, 2013: set max of MXFILT = 30 filters.
c Jun 24, 2013: ignore remapped filter(s)
c Oct 21, 2014: add CAST as input argument
c Jul 13, 2020: MXFILT -> 15
c ------------------------------------

      IMPLICIT NONE

      CHARACTER
     &   PREFIX*(*)   ! (I) prefix for variable names
     &  ,CAST*(*)     ! (I) 'F', 'I', 'D'
     &  ,FILTERS*(*)  ! (I) list of filters; i.e, 'gri'
     &  ,VARLIST*(*)  ! (O) output list of varnames.

      INTEGER LENLIST    ! (O) length of VARLIST

c local var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER NFILT, ifilt, lenv, MXFILT, LENMAX, LENSUM
      INTEGER IFILTOBS
      LOGICAL LTMP
      character varname*32, cfilt*1, c1err*76, c2err*76

c function
      LOGICAL DUPLICATE_FILTER
      INTEGER FILTINDX

C ---------------- BEGIN ----------

      LENMAX = LEN(VARLIST)  ! abort if larger than this
      LENSUM = 0
cc cxxx      MXFILT = 30
      MXFILT = 15

      NFILT = INDEX(FILTERS,' ' ) - 1
      IF ( NFILT > MXFILT ) NFILT = MXFILT
      VARLIST = ''

c -----------
      DO 100 ifilt = 1, NFILT
         cfilt     = FILTERS(ifilt:ifilt)
         LTMP      = DUPLICATE_FILTER(ifilt,FILTERS)

         IFILTOBS = FILTINDX(cfilt // ' ')
         IF( IFILTOBS_REPLACE(IFILTOBS) .NE. IFILTOBS) GOTO 100

         varname   = PREFIX // '_' //  cfilt
         LENV = INDEX(VARNAME,' ') - 1
         if ( LTMP ) VARNAME = VARNAME(1:LENV) // '2'

         LENV = INDEX(VARNAME,' ') - 1
         LENSUM = LENSUM + LENV + 2  ! for error message only

         IF ( ifilt .eq. 1 ) then
            varlist = VARNAME(1:LENV) // ':' // CAST
         else if ( LENSUM < LENMAX ) then
            lenlist = INDEX(varlist,' ') - 1
            varlist = varlist(1:LENLIST) // ',' //
     &            VARNAME(1:LENV) // ':' // CAST
         endif

100   CONTINUE

c ---------------------
c abort if required size (LENSUM) of VARLIST exceed size passed (LENMAX)

      IF ( LENSUM > LENMAX ) THEN
        write(c1err,661) LENSUM, LENMAX
661     format('LENSUM=',I4, ' but LEN(VARLIST)=',I4,
     &          ' is too short.')
        write(c2err,662) PREFIX, NFILT, FILTERS(1:NFILT)
662     format('PREFIX=',A,2x,'NFILT=',I3,'(',A,'+)'  )
        CALL MADABORT("TABLE_VARLIST_FILTERS", c1err, c2err)
      ENDIF

      LENLIST = INDEX(VARLIST,' ') - 1

      RETURN
      END     ! end of TABLE_VARLIST_FILTERS

C ======================================
CDECK  ID>,  TABLE_ADDCOL_LOAD. 
      SUBROUTINE TABLE_ADDCOL_LOAD()

c Created Feb 2017
c Load filter-dependent ADDCOL_XXX arrays.
c Use nominal filter indices, or REMAPED filters if
c &SNLCINP namelist input SNTABLE_FILTER_REMAP is set.

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD

c+CDE,SNHOSTCOM.

C +CDE,TRUECHI2COM. inserted below by ypatchy. 

c for fakes and sim, compute sum[F-Ftrue]^2/sigma^2 per band
c The zeroth element is all bands together.

      REAL
     &   CHI2_TRUEFLUX(0:MXFILT_ALL)
     &  ,PROB_TRUEFLUX(0:MXFILT_ALL)

      INTEGER NDOF_TRUEFLUX(0:MXFILT_ALL)

      COMMON /  TRUECHI2COM /
     &   NDOF_TRUEFLUX, CHI2_TRUEFLUX, PROB_TRUEFLUX


      INTEGER ifilt, NFILT, IFILTOBS, IFILTOBS_REMAP, IFILT_REMAP
      INTEGER LEN
      CHARACTER  CFILTOBS*2, CFILTOBS_REMAP*2, FNAM*18
      LOGICAL DO_NOMINAL, DO_REMAP, VALID_BAND
      LOGICAL USE, USEFILT_REMAP(MXFILT_ALL)
      REAL    SNRMAX, VAL_OLD, VAL_NEW
c function
      INTEGER FILTINDX

C ------------- BEGIN --------------

      FNAM = 'TABLE_ADDCOL_LOAD'

      DO_NOMINAL = ( NFILT_REMAP_TABLE == 0 )
      DO_REMAP   = ( .NOT. DO_NOMINAL)

      NFILT   = NFILTDEF_SURVEY

      IF ( DO_REMAP) THEN
        DO  ifilt=1, MXFILT_ALL
          USEFILT_REMAP(ifilt) = .FALSE.
        ENDDO
      ENDIF

      DO IFILT_REMAP = 1, NFILT_REMAP_TABLE
           ADDCOL_SNRMAX(IFILT_REMAP)     = -9.0
           ADDCOL_XTMW(IFILT_REMAP)       = -9.0
           ADDCOL_FLUXCALMAX(IFILT_REMAP)        = -9.0
           ADDCOL_FLUXCALMAX_ERR(IFILT_REMAP)     = -9.0
           ADDCOL_PROB_TRUEFLUX(IFILT_REMAP)      = -9.0
           ADDCOL_NDOF_TRUEFLUX(IFILT_REMAP)      =  0
           ADDCOL_SNHOST_MAGOBS(IFILT_REMAP,1)    = -9.0
           ADDCOL_SNHOST_MAGOBS(IFILT_REMAP,2)    = -9.0
           ADDCOL_SNHOST_SBFLUXCAL(IFILT_REMAP)   = -9.0
           ADDCOL_SNHOST_SBMAG(IFILT_REMAP)       = -9.0
      ENDDO

      DO 100 ifilt = 1, NFILT
         IFILTOBS = IFILTDEF_MAP_SURVEY(ifilt)
         CFILTOBS = filtdef_string(ifiltobs:ifiltobs)

         IF ( DO_NOMINAL ) then
           ADDCOL_SNRMAX(ifilt)           = SNLC_SNRMAX_FILT(ifilt)
           ADDCOL_XTMW(ifilt)             = SNLC_MWXT_FLUXFRAC(ifilt)
           ADDCOL_FLUXCALMAX(ifilt)       = SNLC_FLUXCALMAX(ifilt)
           ADDCOL_FLUXCALMAX_ERR(ifilt)   = SNLC_FLUXCALMAX_ERR(ifilt)
           ADDCOL_PROB_TRUEFLUX(ifilt)    = PROB_TRUEFLUX(ifilt)
           ADDCOL_NDOF_TRUEFLUX(ifilt)    = NDOF_TRUEFLUX(ifilt)
           ADDCOL_CHI2_FITPKMJD(ifilt)    = CHI2_FITPKMJD(ifilt)
           ADDCOL_SNHOST_MAGOBS(ifilt,1)  = SNHOST_MAGOBS(ifilt,1)
           ADDCOL_SNHOST_MAGOBS(ifilt,2)  = SNHOST_MAGOBS(ifilt,2)
           ADDCOL_SNHOST_SBFLUXCAL(ifilt) = SNHOST_SBFLUXCAL(ifilt)
           ADDCOL_SNHOST_SBMAG(ifilt)     = SNHOST_SBMAG(ifilt)
         ELSE
             ! DO_REMAP
           CALL FILTER_REMAP_FETCH(IFILTOBS,  ! (I)
     &           IFILTOBS_REMAP,IFILT_REMAP)  ! (O)

           SNRMAX         = SNLC_SNRMAX_FILT(ifilt)
           VALID_BAND     = (SNRMAX > -8.999)
           if ( .NOT. VALID_BAND ) GOTO 100

           IFILT_REMAP    = IFILT_REMAP + 1  ! C -> fortran index
           CFILTOBS_REMAP = ADDCOL_FILTERS(ifilt_remap:ifilt_remap)
           USE            = USEFILT_REMAP(IFILTOBS_REMAP)

c check that each band is mapped.
           if ( IFILTOBS_REMAP<0 .or. IFILT_REMAP<0 ) then
             C1ERR = 'Missing REMAP for Band= ' // CFILTOBS(1:1) //
     &          '  for CID=' // SNLC_CCID(1:ISNLC_LENCCID)
             C2ERR = 'Check SNTABLE_FILTER_REMAP in &SNLCINP'
             CALL MADABORT(FNAM, c1err, c2err)
           endif

           USEFILT_REMAP(IFILTOBS_REMAP) = .TRUE.

           VAL_OLD = ADDCOL_SNRMAX(IFILT_REMAP)
           VAL_NEW = SNLC_SNRMAX_FILT(ifilt)
           ADDCOL_SNRMAX(IFILT_REMAP) = MAX(VAL_OLD,VAL_NEW)

           ADDCOL_XTMW(IFILT_REMAP) = SNLC_MWXT_FLUXFRAC(ifilt)
           ADDCOL_PROB_TRUEFLUX(IFILT_REMAP) = PROB_TRUEFLUX(ifilt)
           ADDCOL_NDOF_TRUEFLUX(IFILT_REMAP) = NDOF_TRUEFLUX(ifilt)

           VAL_OLD = ADDCOL_FLUXCALMAX(IFILT_REMAP)
           VAL_NEW = SNLC_FLUXCALMAX(ifilt)
           ADDCOL_FLUXCALMAX(IFILT_REMAP) = MAX(VAL_OLD,VAL_NEW)

           VAL_OLD = ADDCOL_CHI2_FITPKMJD(IFILT_REMAP)
           VAL_NEW = CHI2_FITPKMJD(ifilt)
           ADDCOL_CHI2_FITPKMJD(IFILT_REMAP) = VAL_OLD + VAL_NEW

           ADDCOL_SNHOST_MAGOBS(IFILT_REMAP,1) =
     &            SNHOST_MAGOBS(ifilt,1)      ! any band
           ADDCOL_SNHOST_MAGOBS(IFILT_REMAP,2) =
     &            SNHOST_MAGOBS(ifilt,2)      ! any band
           ADDCOL_SNHOST_SBFLUXCAL(IFILT_REMAP) =
     &            SNHOST_SBFLUXCAL(ifilt)   ! any band
           ADDCOL_SNHOST_SBMAG(IFILT_REMAP) =
     &            SNHOST_SBMAG(ifilt)   ! any band

         ENDIF

100   CONTINUE

      RETURN
      END   ! end TABLE_ADDCOL_LOAD

C ======================================
CDECK  ID>,  TBSTRTERM. 
      SUBROUTINE TABLE_STRING_TERMINATION(OPT)

c Created Jan 2014 by R.Kessler
c For ROOT, terminate strings with char(0) to be used by C++/root code.
c For HBOOK, leave blank-space padding for fortran/hbook code.
c Note that the list of table string-variables is hard-wired;
c initial set is SNLC_CCID and SNLC_FIELDLIST.
c
c Warning: if using both hbook and root, the hbook strings
c          will have lots of extra padding in the ntuple.
c
c OPT > 0 --> add termination
c OPT < 0 --> remove termination
c
c Oct 20 2020: fix index for removing termination char

      IMPLICIT NONE

      INTEGER OPT  ! (I) integer option


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LENCID, LENFLD

C ------------ BEGIN --------------

      IF ( USE_TABLEFILE_ROOT ) THEN
         LENCID  = INDEX(SNLC_CCID,     ' ') - 1
         LENFLD  = INDEX(SNLC_FIELDLIST,' ') - 1

         IF ( OPT > 0 ) THEN
           ! add termination
           SNLC_CCID      = SNLC_CCID(1:LENCID)      // char(0)
           SNLC_FIELDLIST = SNLC_FIELDLIST(1:LENFLD) // char(0)
         ELSE
           ! remove termination char
           SNLC_CCID(LENCID:LENCID)      = ' '
           SNLC_FIELDLIST(LENFLD:LENFLD) = ' '
         ENDIF
      ENDIF

      RETURN
      END

C ===========================================
CDECK  ID>,  TABLE_MARZ. 
      SUBROUTINE TABLE_MARZ(IDTABLE,IFLAG)
c
c Created May 2020 by R.Kessler
c Driver for MARZ table with host-galaxy spectra.
c
c May 3 2021: include GALID as part of NAME
c Nov 16 2023: update text to handle 12 digit GALID instead of 9 digits
c ------------------------------
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,SPECCOM. inserted below by ypatchy. 
c  Apr 2019
c  Read spectra to pass into tables for plotting.
c  Not intended for analysis.

      INTEGER MXVAR_SPECTRUM, MXSPECTRUM, MXLAM_SPECTRUM

      PARAMETER (
     &   MXVAR_SPECTRUM = 10     ! max number of variables after SPEC: key
     &  ,MXSPECTRUM     = 200   ! max number of spectra to read per event
     &  ,MXLAM_SPECTRUM = 20000  ! max number of wave bins per spectrum
     &        )

      LOGICAL RDFLAG_SPECTRUM
      CHARACTER VARNAMES_SPECTRUM(MXVAR_SPECTRUM)*40

      INTEGER
     &    NVAR_SPECTRUM           ! number of spectrum variables to read
     &   ,NSPECTRUM                    ! Number of spectra
     &   ,ID_SPECTRUM(MXSPECTRUM)      ! ID for each spectrum
     &   ,NLAMBIN_SPECTRUM(MXSPECTRUM) ! Number of wave bins per spectrum
     &   ,NLAMBIN_READ                 ! keep track of wave index

      REAL*8
     &    MJD_SPECTRUM(MXSPECTRUM)
     &   ,TOBS_SPECTRUM(MXSPECTRUM)
     &   ,TEXPOSE_SPECTRUM(MXSPECTRUM)
c
     &   ,LAMMIN_SPECTRUM(MXLAM_SPECTRUM)
     &   ,LAMMAX_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAM_SPECTRUM(MXLAM_SPECTRUM)
     &   ,FLAMERR_SPECTRUM(MXLAM_SPECTRUM)
     &   ,SIM_FLAM_SPECTRUM(MXLAM_SPECTRUM)

      COMMON/SPECCOM4/ RDFLAG_SPECTRUM
     &   ,NVAR_SPECTRUM, NSPECTRUM, ID_SPECTRUM, NLAMBIN_SPECTRUM
     &   ,VARNAMES_SPECTRUM, NLAMBIN_READ

      COMMON/SPECCOM8/
     &    MJD_SPECTRUM, TOBS_SPECTRUM, TEXPOSE_SPECTRUM
     &   ,LAMMIN_SPECTRUM, LAMMAX_SPECTRUM
     &   ,FLAM_SPECTRUM, FLAMERR_SPECTRUM, SIM_FLAM_SPECTRUM


C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


      INTEGER IDTABLE  ! (I) table ID
      INTEGER IFLAG    ! (I) see IFLAG_XXX params

c local var

      LOGICAL   DO_FILL
      INTEGER   LENNAME, LENFMT, ISPEC, LENCCID, LENz, LENGALID
      CHARACTER FNAM*12, NAME*40, TEXTFMT*20, TEXTFMT_forC*20
      CHARACTER CCID_forC*40, cGALID*24, cz*20
      REAL      z
      INTEGER*8 GALID
      EXTERNAL SNTABLE_CREATE, SNTABLE_FILL, SPECPAK_DATA

C -------------------- BEGIN -----------------
      FNAM = 'TABLE_MARZ'

      c1err = 'Cannot write MARZ spectra file with fit code'
      c2err = 'MARZFILE_OUT works only with snana.exe '
      CALL MADABORT(FNAM, c1err, c2err)

      IF ( IFLAG .EQ. IFLAG_INI ) THEN
         NAME     = 'MARZ' // char(0)
         LENNAME  = INDEX(NAME,    ' ') - 1
         TEXTFMT_forC = 'FITS' // char(0)
         LENFMT       =  4
         CALL SNTABLE_CREATE(IDTABLE, NAME, TEXTFMT_forC,
     &          LENNAME,LENFMT)  ! C fun

         RETURN
      ENDIF

c --------------------------
c fill table.

      DO_FILL = LSNCUTS
      IF ( DO_FILL ) THEN
         ISPEC = 1
         LENCCID   = ISNLC_LENCCID
         CCID_forC = SNLC_CCID(1:LENCCID)
         if ( LSIM_SNANA ) then
            z      = SIM_REDSHIFT_HELIO
            GALID  = SIM_HOSTLIB_GALID
            cGALID ='GALID=None'

            write(cz,41) z
 41         format('z=',F5.3)
            if ( SIM_HOSTLIB_GALID > 0 ) then
               write(cGALID,44) SIM_HOSTLIB_GALID
 44            format('GALID=', I12.12 )
            endif

            LENz     = INDEX(cz,' ') - 1
            LENGALID = INDEX(cGALID,' ') - 1

            write(CCID_forC,40) SNLC_CCID(1:LENCCID),
     &          cz(1:LENz), cGALID(1:LENGALID)
40          format(A, '[', A, ',', A, ']' )
            LENCCID = LENCCID + LENz + LENGALID + 3


         endif

         write(6,10) CCID_forC(1:LENCCID)
 10      format(T8,'SPECPLOT: pack CID=',A,' for MARZ table.')

         CCID_forC = CCID_forC(1:LENCCID) // char(0)

         CALL RDSPEC_DRIVER(ISPEC)  ! Apr 5 2021

         CALL SPECPAK_DATA(
     &         CCID_forC
     &       , ID_SPECTRUM(ispec)
     &       , MJD_SPECTRUM(ispec)
     &       , TOBS_SPECTRUM(ispec)    ! May 7 2019
     &       , TEXPOSE_SPECTRUM(ispec)
     &       , NLAMBIN_SPECTRUM(ispec)
     &       , LAMMIN_SPECTRUM
     &       , LAMMAX_SPECTRUM
     &       , FLAM_SPECTRUM
     &       , FLAMERR_SPECTRUM
     &       , LENCCID )

          CALL SPECPAK_FILL(CCID_forC, LENCCID)
      ENDIF

      RETURN
      END    ! end of TABLE_MARZ


C =============================================
CDECK  ID>,  CWNDUP. 
      LOGICAL FUNCTION DUPLICATE_FILTER(i1,FILTERS)

c Created Sep 29, 2012
c Return TRUE if any previous filter in FILTERS
c is defined after using LOCASE on both filters.
c
c Example 1: i1=3 and FILTERS='ugrizUGRIZ'
c            i1=3 corresponds to r, and previous filters are unique.
c                --> returns FALSE since there are no duplicates.
c
c Example 2: i1=8 and FILTERS='ugrizUGRIZ'
c            i1=8 corresponds to R, which is the same as 'r' after
c            converting to lower case --> returns TRUE.
c
c ------------------------------------------
      IMPLICIT NONE

      INTEGER i1             ! (I) check this filter in the list
      CHARACTER FILTERS*(*)  ! (I) list of filster; i.e, 'gri'

c local var

      INTEGER i2
      character cfilt1*2, cfilt2*2, cfilt1_lower*2, cfilt2_lower*2

c ----------------- BEGIN ------------

      DUPLICATE_FILTER = .FALSE.

      if ( i1 .eq. 1 ) return

      cfilt1      = FILTERS(i1:i1)
      CALL LOCASE(cfilt1, cfilt1_lower)

      DO i2 = 1, i1-1
         cfilt2      = FILTERS(i2:i2)
         CALL LOCASE(cfilt2, cfilt2_lower)
         if ( cfilt1_lower .EQ. cfilt2_lower ) then
            DUPLICATE_FILTER = .TRUE.
            return
         endif
      ENDDO

      RETURN
      END

C ================================================
CDECK  ID>,  INITGALXT. 
      SUBROUTINE INIT_GALextinct()

c Created Sep 19 2013 by R.Kessler
c
c - Hierarchy of OPT_MWCOLORLAW (and RV) for data, in order of priority
c    -> OPT_MWCOLORLAW         (if >=0 -> read from &SNLCINP namelist)
c    -> OPT_MWCOLORLAW_DEFAULT
c
c - Hierarchy of OPT_MWCOLORLAW for sim
c    -> OPT_MWCOLORLAW         (if >=0 -> read from &SNLCINP namelist)
c    -> SIMOPT_MWCOLORLAW      (from sim files)
c
c
c - ABORT on invalid option
c
c - print info for colorLaw and MWEBV-updates
c
c ------------------------------------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


      LOGICAL   LDATA, SETMWCL_USER, SETEBV_USER, SETRV_USER
      INTEGER   LENTEXT
      CHARACTER nameOpt*20, CTEXT*60
      EXTERNAL  text_MWoption

C ---------------- BEGIN -----------

      CALL PRBANNER("INIT_GALextinct")

      LDATA         = .NOT. LSIM_SNANA
      SETMWCL_USER  = ( OPT_MWCOLORLAW  > -1   )
      SETEBV_USER   = ( OPT_MWEBV       > -1   )
      SETRV_USER    = ( RV_MWCOLORLAW   > -0.01 )

c ---------------------------------

      IF ( LDATA ) THEN

c     ---------- check RV ---------
         if ( SETRV_USER ) then
            write(6,22) RV_MWCOLORLAW, 'User (&SNLCINP)'
         else
            RV_MWCOLORLAW = RV_MWCOLORLAW_DEFAULT
            write(6,22) RV_MWCOLORLAW, 'Default'
         endif

c     --------- check color law ------------
         if ( SETMWCL_USER ) then
            write(6,20) OPT_MWCOLORLAW, 'User (&SNLCINP)'
         else
            OPT_MWCOLORLAW = OPT_MWCOLORLAW_DEFAULT
            write(6,20) OPT_MWCOLORLAW, 'Default'
         endif

      ENDIF


      IF ( LSIM_SNANA ) THEN

         if ( SETRV_USER ) then
            write(6,22) RV_MWCOLORLAW, 'User (&SNLCINP)'
         else
            ! use simulated RV if not set by user
            RV_MWCOLORLAW = SIM_MWRV
            write(6,22) RV_MWCOLORLAW, 'Simulation'
         endif

         if ( SETMWCL_USER ) then
            write(6,20) OPT_MWCOLORLAW, 'User (&SNLCINP)'
         else
            ! use simulated color law if not set by user
            OPT_MWCOLORLAW = SIMOPT_MWCOLORLAW
            write(6,20) OPT_MWCOLORLAW, 'Simulation'
         endif

      ENDIF

 20   format(T5, 'OPT_MWCOLORLAW -> ',I3   , ' from ', A)
 22   format(T5, 'RV_MWCOLORLAW  -> ',F5.2 , ' from ', A)


      nameOpt = "COLORLAW" // char(0)
      call text_MWoption(nameOpt, OPT_MWCOLORLAW, CTEXT, 8,40)

      LENTEXT = INDEX(CTEXT,char(0)) - 1
      write(6,30) OPT_MWCOLORLAW, CTEXT(1:LENTEXT)
 30   format(T5,'OPT_MWCOLORLAW =  ', I3,' -> ', A )
      call flush(6)

c ---------------------------------------------
c check for option to modify MWEBV;

      print*,' '


      IF ( LDATA ) THEN
         if ( SETEBV_USER ) then
            write(6,21) OPT_MWEBV, 'User (&SNLCINP)'
         else
         ! use default MWEBV map if not set by user
            OPT_MWEBV = OPT_MWEBV_DEFAULT
            write(6,21) OPT_MWEBV, 'Default'
         endif
      ENDIF

 21   format(T5, 'OPT_MWEBV -> ',I3,' from ', A)

      IF ( LSIM_SNANA ) THEN
         if ( SETEBV_USER ) then
            write(6,21) OPT_MWEBV, 'User (&SNLCINP)'
         else
         ! use simulated MWEBV value if option is not set by user
            OPT_MWEBV = 1       ! don't change  MWEBV in sim-data file
            write(6,21) SIMOPT_MWEBV, 'Simulation'
         endif
      ENDIF

      nameOpt = "EBV" // char(0)
      call text_MWoption(nameOpt, OPT_MWEBV, CTEXT, 3,40)
      LENTEXT = INDEX(CTEXT,char(0)) - 1
      write(6,40) OPT_MWEBV, CTEXT(1:LENTEXT)
 40   format(T5,'OPT_MWEBV =  ',I3,' -> ', A )
      call flush(6)

      RETURN
      END     ! end of INIT_GALextinct()

C =======================
CDECK  ID>,  NEAREST_IFILTDEF_WRAPPER. 
      INTEGER FUNCTION NEAREST_IFILTDEF_WRAPPER(
     &   OPT          ! (I) option; see below
     &  ,ifiltdef     ! (I) observer filter index
     &  ,rank_want    ! (I) 1=nearest, 2=2nd nearest, 3=3rd nearest
     &  ,Z            ! (I) redshift
     &  ,LAMDIF_MIN   ! (O) min lam-distance (A)
     &    )

c
c Created Nov 2022
c Temporary wrapper to select either LEGACY/fortran function,
c or REFACTORED/C function. This function should be removed
c after the transistion to refactored code.

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER OPT, IFILTDEF, RANK_WANT
      REAL    z,  LAMDIF_MIN
      REAL*8  z8, LAMDIF_MIN8

      CHARACTER FNAM*32
      INTEGER NEAREST_IFILT_REST     ! lefacy fortran func
      INTEGER NEAREST_IFILTDEF_REST  ! refactored C code
C ------------- BEGIN -------------

         z8 = DBLE(z)
         FNAM = 'NEAREST_IFILTDEF_WRAPPER' // char(0)
         NEAREST_IFILTDEF_WRAPPER =
     &   NEAREST_IFILTDEF_REST(OPT, IFILTDEF,RANK_WANT,
     &                         z8, FNAM, LAMDIF_MIN8, 32)
         LAMDIF_MIN = SNGL(LAMDIF_MIN8)


      RETURN
      END     ! end NEAREST_IFILTDEF_WRAPPER


C =======================================
CDECK  ID>,  FUPDDRIV. 
      SUBROUTINE FILTER_UPDATE_DRIVER()
c
c Nov 8, 2010 R.Kessler
c
c --------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



c local var

      INTEGER IFILT, IFILT_OBS, OPT
      LOGICAL LSAME, LUPD, ISBX
      CHARACTER C1ERR*80, C2err*80

c function
      LOGICAL ISBXFILT
C ------------- BEGIN ----------

      OPT = OPT_FILTER_UPDATE
      IF ( OPT .LE. 0 ) RETURN

      write(6,20) SNLC_CCID(1:ISNLC_LENCCID)
 20   format(T5,'***** UPDATE FILTER TRANSMISSION FOR CID = ',
     &       A, ' ***** ')


      LUPD = ( OPT .EQ. OPT_FILTUPD_EACHSN ) .or.
     &       ( OPT .EQ. OPT_FILTUPD_MAP    )

c determine path with filter update; set global FILTER_UPDATE_DIR
c Make sure to do this outside the IFILT loop to avoid redundant
c loops through the maps.
      IF ( LUPD ) CALL GET_FILTER_UDPATE_DIR(SNLC_CCID)

c -----------------------------------------
c update filter transmissions based on option

      DO 10 IFILT = 1, NFILTDEF_SURVEY

        if ( ISNLC_NEPOCH_FILT(ifilt) .LE. 0 ) GOTO 10

        ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
        DOFLAG_FILTER_UPDATE(ifilt_obs) = OPT_FILTER_UPDATE

        ISBX      = ISBXFILT(ifilt_obs,'', 'OBS' )

        LSAME = (OPT .EQ. OPT_FILTUPD_SAMEFILT)  .or. ISBX

        if ( LSAME  ) then
            ! fancy way to use same filter response for each SN
           CALL FILTER_UPDATE_SAMEFILT(ifilt)
        else if ( LUPD ) then
           CALL FILTER_UPDATE_EACHSN(ifilt)

        else
           write(c1err,60) OPT
60         format('Invalid  OPT_FILTER_UPDATE = ', I3 )
           c2err = 'Check OPT_FILTUPD_*  parameters in snana.car'
           CALL MADABORT("FILTER_UPDATE_DRIVER", C1ERR, C2ERR)
        endif

 10   CONTINUE


c ----------------------------------------------------
c  Finally, update ZP offsets for all filters.

      IF ( LUPD ) THEN
        CALL FILTER_UPDATE_ZPOFF()
      ENDIF

c later add stuff for K-corrections ...

      RETURN
      END

C ====================================
CDECK  ID>,  FUPDZP. 
      SUBROUTINE FILTER_UPDATE_ZPOFF()

c Created July 2011
c Update MAGOBS_SHIFT_ZP_FILT(ifilt_obs) based on the
c zeropoint (AB) offsets in text-file $FDIR/ZPOFF.DAT .
c If this ZPOFF.DAT file does not exist, then just set
c the offsets to the user offsets.
c
c -------------

      IMPLICIT NONE


c local args


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID


c+CDE,PARSECOM.

      INTEGER IFILT, IFILT_OBS
      REAL ZPOFF_UPD(MXFILT_ALL)

C --------------- BEGIN -------------

       DO ifilt  = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          ZPOFF_UPD(ifilt_obs) = 0.0
       ENDDO

c update ZP-shift for each filter (i.e., add to user-shift)
      DO ifilt  = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         MAGOBS_SHIFT_ZP_FILT(ifilt_obs) =
     &   MAGOBS_SHIFT_ZP_USER(ifilt_obs) + ZPOFF_UPD(ifilt_obs)
      ENDDO

      CALL DMP_ZPOFF

      RETURN
      END  ! end FILTER_UPDATE_ZPOFF

C ================================================
CDECK  ID>,  GTFUPDDIR. 
      SUBROUTINE GET_FILTER_UDPATE_DIR(CCID)

c Created May 18, 2012
c Find and load global  FILTER_UPDATE_DIR for this CCID.
c Used for filter-update option.

      IMPLICIT NONE

      CHARACTER CCID*(*)  ! (I) SN name

c local var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



      INTEGER LPDIR, LSDIR, LPATH, LCC, LMAP, IMAP1, IMAP2
      CHARACTER MAPDIR*100
c functions
      INTEGER IMAP2_FUPDMATCH

C -------------------- BEGIN --------------

      LCC   = INDEX(CCID,' ') - 1
      LPDIR = INDEX(PREFIX_UPD_FILTDIR,' ') -1
      LSDIR = INDEX(SUFFIX_UPD_FILTDIR,' ') -1
      LPATH = INDEX(FILTER_UPDATE_TOPDIR,' ') - 1


      if ( OPT_FILTER_UPDATE .EQ. OPT_FILTUPD_EACHSN ) then
         FILTER_UPDATE_DIR = FILTER_UPDATE_TOPDIR(1:LPATH) // '/'
     &        // PREFIX_UPD_FILTDIR(1:LPDIR)
     &        // CCID(1:LCC)
     &        // SUFFIX_UPD_FILTDIR(1:LSDIR)

      else if ( OPT_FILTER_UPDATE .EQ. OPT_FILTUPD_MAP ) then

c search 2nd map for CCID match to get IMAP1

         IMAP2   = IMAP2_FUPDMATCH(CCID)
         IMAP1   = MAP2_FILTER_UPDATE_PTRMAP1(IMAP2)
         MAPDIR  = MAP1_FILTER_UPDATE_SUBDIR(IMAP1)
         LMAP    = INDEX(MAPDIR,' ') - 1
         FILTER_UPDATE_DIR = FILTER_UPDATE_TOPDIR(1:LPATH) // '/'
     &             // MAPDIR(1:LMAP)

      endif

      RETURN
      END

C ================================================
CDECK  ID>,  FUPD_EACHSN. 
      SUBROUTINE FILTER_UPDATE_EACHSN(ifilt)

c Nov 8, 2010
c Read/update filter response for this sparse 'ifilt'
c Store in FILTOBS_TRANS_UPD array using same lambda
c binning as in KCOR file. Updated lambda binning
c can be different since it gets interpolated to the
c original grid.
c
c Nov 2022: refactor to use new & old kcor/calib code.
c Dec 2023: remove fortran OPEN and rely on rd2column to read gzipped or unzipped files.
c

      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID


c +CDE,PARSECOM.

c subroutine args
      INTEGER IFILT     ! (I) sparse indices

c local var

      INTEGER
     &   IFILT_OBS, L0, LCC, LREF, LSN, LDIR, LTMPF, LCOM
     &  ,LPSN, LPREF, LSSN, LSREF, ilam, NLAM_UPD, NLAM_STORE
     &  ,istat, MXLAM, OPT_INTERP, OPT_FRAME, OPT_RD2COL

      CHARACTER
     &   FILTFILE_SN*(MXCHAR_FILENAME)   ! SN tranmission vs. lambda
     &  ,FILTFILE_REF*(MXCHAR_FILENAME)  ! idem for primary ref
     &  ,TMPFILE*(MXCHAR_FILENAME)
     &  ,CCID*(MXCHAR_CCID)
     &  ,cfilt*1
     &  ,c1err*80
     &  ,c2err*80
     &  ,comment*40

      REAL*8
     &   LAM
     &  ,FLAM_UPD(MXLAMBIN_FILT)    ! temp lambda array
     &  ,FTRANS_UPD(MXLAMBIN_FILT)  ! temp filterTrans array
     &  ,Trans_upd
     &  ,FLAM_STORE(MXLAMBIN_FILT) ! store trans on this lam array
     &  ,FTRANSSN_STORE(MXLAMBIN_FILT)
     &  ,FTRANSREF_STORE(MXLAMBIN_FILT)

      LOGICAL  LEXIST_SN, LEXIST_REF, UPD_DUMP

c define utilities from sntools.c
      INTEGER  RD2COLUMNFILE
      EXTERNAL RD2COLUMNFILE

      REAL*8   INTERP_1DFUN
      EXTERNAL INTERP_1DFUN
      EXTERNAL LOAD_FILTERTRANS_CALIB, GET_CALIB_FILTERLAM

C ---------------- BEGIN --------------

      UPD_DUMP = .FALSE.  ! internal dump logical

      ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
      cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
      LCC       = INDEX(SNLC_CCID, ' '     ) - 1
      CCID      = SNLC_CCID(1:LCC)


       OPT_FRAME = OPT_FILTOBS - 1
       CALL  GET_CALIB_FILTERLAM(OPT_FRAME, IFILT_OBS,
     &                      NLAM_STORE, FLAM_STORE)


c - - - - -
      if (UPD_DUMP) then
        print*,' '
        print*, 'XXXXXX ----------------------------------------- '
        print*, 'XXXXXX FILTER_UPDATE_EACHSN  DUMP start for ',
     &       CCID(1:LCC),'-', cfilt
        call flush(6)
      end if

      OPT_INTERP = 1   ! 1=linear;  2=quadratic

      comment = CCID(1:LCC) // '-filter-update' // char(0)
      LCOM    = INDEX(comment,' ') - 1

c     get string lengths for file name

      LPSN  = INDEX(PREFIX_UPD_TRANSSN,' ') -1
      LSSN  = INDEX(SUFFIX_UPD_TRANSSN,' ') -1

      LPREF = INDEX(PREFIX_UPD_TRANSREF,' ') -1
      LSREF = INDEX(SUFFIX_UPD_TRANSREF,' ') -1

      L0    = INDEX(FILTER_UPDATE_PATH, ' ' ) - 1
      LDIR = INDEX(FILTER_UPDATE_DIR,' ') - 1

c construct full filename of SN and REF-transmission files.

      TMPFILE = PREFIX_UPD_TRANSSN(1:LPSN)
     &           // cfilt // SUFFIX_UPD_TRANSSN(1:LSSN)
      LTMPF = INDEX(TMPFILE,' ') - 1
      FILTFILE_SN = FILTER_UPDATE_DIR(1:LDIR)
     &                 // '/' // TMPFILE(1:LTMPF)

      TMPFILE = PREFIX_UPD_TRANSREF(1:LPREF)
     &          // cfilt // SUFFIX_UPD_TRANSREF(1:LSREF)
      LTMPF = INDEX(TMPFILE,' ') - 1
      FILTFILE_REF = FILTER_UPDATE_DIR(1:LDIR)
     &          // '/' // TMPFILE(1:LTMPF)


      if ( UPD_DUMP ) then
        print*, '++++ UPDATING FILTER '
     &          ,'IFILT = ', ifilt_obs,' '
     &         , cfilt(1:1), ' with NLAM '
     &         , NLAM_STORE , ' for SN ', CCID
        call flush(6)
       end if


c Use IOSTAT option to figure out which of the files
c FILTFILE_REF  and FILTFILE_SN exist

      OPT_RD2COL = 1  ! rd2columun does NOT abort on missing file

c     check if FILTFILE_REF exists?


      MXLAM   = MXLAMBIN_FILT
      LREF    = INDEX(FILTFILE_REF,' ') - 1
      TMPFILE = FILTFILE_REF(1:LREF) // char(0)
      istat   = rd2columnFile (TMPFILE, MXLAM, NLAM_UPD,
     &                 FLAM_UPD, FTRANS_UPD, OPT_RD2COL, LREF)  ! (out)
      LEXIST_REF = (istat > 0 )

      if (UPD_DUMP) then
        print*, '  LEXIST_REF = ', LEXIST_REF,' for ', CCID
        call flush(6)
      end if

c - - - - - -
c    now interpolate to the original grid
c    for files which exist

      IF ( LEXIST_REF ) THEN
        DO 20 ilam = 1, NLAM_STORE
            FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) = 0.0

            LAM = FLAM_STORE(ilam)
            FTRANSREF_STORE(ilam) = 0.0

            if ( LAM .LT. FLAM_UPD(1)        ) GOTO 20
            if ( LAM .GT. FLAM_UPD(NLAM_UPD) ) GOTO 20

            Trans_upd = interp_1dfun(OPT_INTERP, LAM,
     &                  NLAM_UPD, FLAM_UPD, FTRANS_UPD, comment, LCOM)

            FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) = sngl(Trans_upd)
            FTRANSREF_STORE(ilam)  = Trans_upd

20      CONTINUE  ! ILAM loop over original lambda binning
        if (UPD_DUMP) then
          print*, "REF interp done"
          call flush(6)
        end if

      ENDIF  ! end LEXIST_REF


c ------------------------------------
c     FILTFILE_SN exists?

      LSN     = INDEX(FILTFILE_SN,' ') - 1
      MXLAM   = MXLAMBIN_FILT
      TMPFILE = FILTFILE_SN(1:LSN) // char(0)
      istat   = rd2columnFile (TMPFILE, MXLAM, NLAM_UPD,
     &                 FLAM_UPD, FTRANS_UPD, OPT_RD2COL, LSN)  ! (out)
      LEXIST_SN = (istat > 0 )

c - - - - - - -
c   INTERPOLATE to get FILTOBS_TRANSSN_UPD

      IF (LEXIST_SN) THEN
cc      print*, ' Interpolate SN file', NLAM_STORE
        DO 70 ilam = 1, NLAM_STORE
            FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) = 0.0

            LAM = FLAM_STORE(ilam)
            FTRANSSN_STORE(ilam) = 0.0

            if ( LAM .LT. FLAM_UPD(1)        ) GOTO 70
            if ( LAM .GT. FLAM_UPD(NLAM_UPD) ) GOTO 70

            Trans_upd = interp_1DFUN(OPT_INTERP, LAM,
     &             NLAM_UPD, FLAM_UPD, FTRANS_UPD, comment, LCOM )

            FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) = sngl(Trans_upd)
            FTRANSSN_STORE(ilam) = Trans_upd

70      CONTINUE  ! ILAM loop over original lambda binning
        if (UPD_DUMP) then
          print*, 'SN Interp done for', NLAM_STORE, CCID
          call flush(6)
        end if
      ENDIF


c    If neither file exists, abort program


      if (.NOT.( LEXIST_REF .OR. LEXIST_SN) ) then
        c1err = 'Could not update filter-trans for CID = '
     &       // CCID(1:LCC) // '-' // cfilt
        c2err = 'FILTDIR=' // FILTER_UPDATE_DIR(1:LDIR)
        CALL MADABORT('FILTER_UPDATE_EACHSN', c1err, c2err )
      endif

c     IF either SN or REF file does not exist, copy the other
c     file for the transmission functions


c     SN File does not exist. IF REF file exists, SN trans= Ref Trans
c                             IF REF file does not exist, SN trans undef
c                             but should have been aborted above

      if (.NOT. LEXIST_SN ) then
        DO 170 ilam = 1, NLAM_STORE
            FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) =
     &      FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS)

            FTRANSSN_STORE(ilam) = FTRANSREF_STORE(ilam)
170     CONTINUE  ! ILAM loop over original lambda binning
      end if


c - - - - - - - - -
c     REF File does not exist. IF SN file exists, Ref trans= SN Trans
c                             IF SN file does not exist, Ref trans undef
c                             but should have been aborted above
      IF (.NOT. LEXIST_REF ) THEN
        DO 270 ilam = 1, NLAM_STORE
            LAM  = FILTOBS_LAMBDA(ilam,IFILT_OBS)
            FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) =
     &      FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS)

            FTRANSREF_STORE(ilam) = FTRANSSN_STORE(ilam)
270      CONTINUE  ! ILAM loop over original lambda binning
      ENDIF

      if ( USE_KCOR_REFACTOR ) then
         CALL LOAD_FILTERTRANS_CALIB(OPT_FRAME, IFILT_OBS, NLAM_STORE,
     &         FLAM_STORE, FTRANSSN_STORE )
      endif

c -----------------------------
      if ( UPD_DUMP ) then
        print*, '%%%% ', NLAM_STORE
        if (mod(NLAM_STORE,2).EQ.0) then
           ilam = NLAM_STORE/2
        else
         ilam = (NLAM_STORE+1)/2
        end if
        LAM  = FILTOBS_LAMBDA(ilam,IFILT_OBS)
        print*, 'xxxxx', NLAM_STORE
     &        , sngl(FTRANSSN_STORE(ilam))
     &        , sngl(FTRANSREF_STORE(ilam))

        print*, 'xxxx SN =' , CCID
        print*, 'xxxx LEXIST_REF =', LEXIST_REF
        print*, 'xxxx LEXIST_SN  =', LEXIST_SN
        print*, 'xxxx FILE_REF   =', FILTFILE_REF
        print*, 'xxxx FILE_SN    =', FILTFILE_SN

        print*, 'XXXXXX FILTER_UPDATE_EACHSN  DUMP end for ', CCID
        call flush(6)
      endif


      RETURN
      END   ! end FILTER_UPDATE_EACHSN


C ================================================
CDECK  ID>,  FUPD_EACHSN_LEGACY. 
      SUBROUTINE FILTER_UPDATE_EACHSN_LEGACY(ifilt)

c Nov 8, 2010
c Read/update filter response for this sparse 'ifilt'
c Store in FILTOBS_TRANS_UPD array using same lambda
c binning as in KCOR file. Updated lambda binning
c can be different since it gets interpolated to the
c original grid.
c
c Nov 2022: refactor to use new & old kcor/calib code.
c

      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID


c +CDE,PARSECOM.

c subroutine args
      INTEGER IFILT     ! (I) sparse indices

c local var

      INTEGER
     &   IFILT_OBS, L0, LCC, LL, LDIR, LTMPF, LCOM
     &  ,LPSN, LPREF, LSSN, LSREF, ilam, NLAM_UPD, NLAM_STORE
     &  ,istat, MXLAM, OPT_INTERP, OPT_FRAME, OPT_RD2COL

      CHARACTER
     &   FILTFILE_SN*(MXCHAR_FILENAME)   ! SN tranmission vs. lambda
     &  ,FILTFILE_REF*(MXCHAR_FILENAME)  ! idem for primary ref
     &  ,TMPFILE*(MXCHAR_FILENAME)
     &  ,CCID*(MXCHAR_CCID)
     &  ,cfilt*1
     &  ,c1err*80
     &  ,c2err*80
     &  ,comment*40

      REAL*8
     &   LAM
     &  ,FLAM_UPD(MXLAMBIN_FILT)    ! temp lambda array
     &  ,FTRANS_UPD(MXLAMBIN_FILT)  ! temp filterTrans array
     &  ,Trans_upd
     &  ,FLAM_STORE(MXLAMBIN_FILT) ! store trans on this lam array
     &  ,FTRANSSN_STORE(MXLAMBIN_FILT)
     &  ,FTRANSREF_STORE(MXLAMBIN_FILT)

      LOGICAL  LEXIST_SN, LEXIST_REF, UPD_DUMP

c define utilities from sntools.c
      INTEGER  RD2COLUMNFILE
      EXTERNAL RD2COLUMNFILE

      REAL*8   INTERP_1DFUN
      EXTERNAL INTERP_1DFUN
      EXTERNAL LOAD_FILTERTRANS_CALIB, GET_CALIB_FILTERLAM

C ---------------- BEGIN --------------

      UPD_DUMP = .FALSE.  ! internal dump logical

      ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
      cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
      LCC       = INDEX(SNLC_CCID, ' '     ) - 1
      CCID      = SNLC_CCID(1:LCC)

      IF ( USE_KCOR_LEGACY ) THEN
        NLAM_STORE = NLAMBIN_FILTOBS(ifilt_obs)
        DO ilam = 1, NLAM_STORE
           FLAM_STORE(ilam) =
     &           DBLE( FILTOBS_LAMBDA(ilam,IFILT_OBS) )
        ENDDO
      ELSE
        ! refac C code
        OPT_FRAME = OPT_FILTOBS - 1
        CALL  GET_CALIB_FILTERLAM(OPT_FRAME, IFILT_OBS,
     &                      NLAM_STORE, FLAM_STORE)
      ENDIF

c - - - - -
      if (UPD_DUMP) then
        print*,' '
        print*, 'XXXXXX ----------------------------------------- '
        print*, 'XXXXXX FILTER_UPDATE_EACHSN  DUMP start for ',
     &       CCID(1:LCC),'-', cfilt
        call flush(6)
      end if

      OPT_INTERP = 1   ! 1=linear;  2=quadratic

      comment = CCID(1:LCC) // '-filter-update' // char(0)
      LCOM    = INDEX(comment,' ') - 1

c     get string lengths for file name

      LPSN  = INDEX(PREFIX_UPD_TRANSSN,' ') -1
      LSSN  = INDEX(SUFFIX_UPD_TRANSSN,' ') -1

      LPREF = INDEX(PREFIX_UPD_TRANSREF,' ') -1
      LSREF = INDEX(SUFFIX_UPD_TRANSREF,' ') -1

      L0    = INDEX(FILTER_UPDATE_PATH, ' ' ) - 1
      LDIR = INDEX(FILTER_UPDATE_DIR,' ') - 1

c construct full filename of SN and REF-transmission files.

      TMPFILE = PREFIX_UPD_TRANSSN(1:LPSN)
     &           // cfilt // SUFFIX_UPD_TRANSSN(1:LSSN)
      LTMPF = INDEX(TMPFILE,' ') - 1
      FILTFILE_SN = FILTER_UPDATE_DIR(1:LDIR)
     &                 // '/' // TMPFILE(1:LTMPF)

      TMPFILE = PREFIX_UPD_TRANSREF(1:LPREF)
     &          // cfilt // SUFFIX_UPD_TRANSREF(1:LSREF)
      LTMPF = INDEX(TMPFILE,' ') - 1
      FILTFILE_REF = FILTER_UPDATE_DIR(1:LDIR)
     &          // '/' // TMPFILE(1:LTMPF)


      if ( UPD_DUMP ) then
        print*, '++++ UPDATING FILTER '
     &          ,'IFILT = ', ifilt_obs,' '
     &         , cfilt(1:1), ' with NLAM '
     &         , NLAM_STORE , ' for SN ', CCID
        call flush(6)
       end if


      OPT_RD2COL = 1

c Use IOSTAT option to figure out which of the files
c FILTFILE_REF  and FILTFILE_SN exist

c     check if FILTFILE_REF exists?

      istat=1
      LL = INDEX(FILTFILE_REF,' ') - 1
      TMPFILE =FILTFILE_REF(1:LL)
      OPEN(UNIT=LUNTMP, FILE=TMPFILE, STATUS='OLD',
     &      IOSTAT=istat)
      CLOSE( UNIT = LUNTMP)

      if (istat .EQ. 0) then
         LEXIST_REF = .true.
         MXLAM   = MXLAMBIN_FILT
         TMPFILE = FILTFILE_REF(1:LL) // char(0)
         istat   = rd2columnFile (TMPFILE, MXLAM, NLAM_UPD
     &            ,FLAM_UPD, FTRANS_UPD, OPT_RD2COL, LL)  ! (out)

      else
          LEXIST_REF = .false.
      endif

      if (UPD_DUMP) then
        print*, '  LEXIST_REF = ', LEXIST_REF,' for ', CCID
        call flush(6)
      end if

c - - - - - -
c    now interpolate to the original grid
c    for files which exist

      IF ( LEXIST_REF ) THEN
        DO 20 ilam = 1, NLAM_STORE
            FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) = 0.0

            LAM = FLAM_STORE(ilam)
            FTRANSREF_STORE(ilam) = 0.0

            if ( LAM .LT. FLAM_UPD(1)        ) GOTO 20
            if ( LAM .GT. FLAM_UPD(NLAM_UPD) ) GOTO 20

            Trans_upd = interp_1dfun(OPT_INTERP, LAM,
     &                  NLAM_UPD, FLAM_UPD, FTRANS_UPD, comment, LCOM)

            FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) = sngl(Trans_upd)
            FTRANSREF_STORE(ilam)  = Trans_upd

20      CONTINUE  ! ILAM loop over original lambda binning
        if (UPD_DUMP) then
          print*, "REF interp done"
          call flush(6)
        end if

      ENDIF  ! end LEXIST_REF


c ------------------------------------
c     FILTFILE_SN exists?


      istat=1
      LL = INDEX(FILTFILE_SN,' ') - 1
      TMPFILE =FILTFILE_SN(1:LL)
      OPEN(UNIT=LUNTMP, FILE=TMPFILE, STATUS='OLD',
     &  IOSTAT=istat)

      if (istat.EQ.0) then
         LEXIST_SN = .true.
c        readsnfile
         MXLAM   = MXLAMBIN_FILT
         TMPFILE = FILTFILE_SN(1:LL) // char(0)
         istat   = rd2columnFile (TMPFILE, MXLAM, NLAM_UPD
     &            ,FLAM_UPD, FTRANS_UPD, OPT_RD2COL, LL)  ! (out)
      else
         LEXIST_SN = .false.
      endif

      CLOSE( UNIT = LUNTMP)

c - - - - - - -
c   INTERPOLATE to get FILTOBS_TRANSSN_UPD

      IF (LEXIST_SN) THEN
cc      print*, ' Interpolate SN file', NLAM_STORE
        DO 70 ilam = 1, NLAM_STORE
            FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) = 0.0 ! xxx mark later

            LAM = FLAM_STORE(ilam)
            FTRANSSN_STORE(ilam) = 0.0

            if ( LAM .LT. FLAM_UPD(1)        ) GOTO 70
            if ( LAM .GT. FLAM_UPD(NLAM_UPD) ) GOTO 70

            Trans_upd = interp_1DFUN(OPT_INTERP, LAM,
     &             NLAM_UPD, FLAM_UPD, FTRANS_UPD, comment, LCOM )

            FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) = sngl(Trans_upd) ! xxx mark
            FTRANSSN_STORE(ilam) = Trans_upd

70      CONTINUE  ! ILAM loop over original lambda binning
        if (UPD_DUMP) then
          print*, 'SN Interp done for', NLAM_STORE, CCID
          call flush(6)
        end if
      ENDIF


c    If neither file exists, abort program


      if (.NOT.( LEXIST_REF .OR. LEXIST_SN) ) then
        c1err = 'Could not update filter-trans for CID = '
     &       // CCID(1:LCC) // '-' // cfilt
        c2err = 'FILTDIR=' // FILTER_UPDATE_DIR(1:LDIR)
        CALL MADABORT('FILTER_UPDATE_EACHSN', c1err, c2err )
      endif

c     IF either SN or REF file does not exist, copy the other
c     file for the transmission functions


c     SN File does not exist. IF REF file exists, SN trans= Ref Trans
c                             IF REF file does not exist, SN trans undef
c                             but should have been aborted above

      if (.NOT. LEXIST_SN ) then
        DO 170 ilam = 1, NLAM_STORE
            FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) =  ! xxx mark
     &      FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS)   ! xxx mark

            FTRANSSN_STORE(ilam) = FTRANSREF_STORE(ilam)
170     CONTINUE  ! ILAM loop over original lambda binning
      end if


c - - - - - - - - -
c     REF File does not exist. IF SN file exists, Ref trans= SN Trans
c                             IF SN file does not exist, Ref trans undef
c                             but should have been aborted above
      IF (.NOT. LEXIST_REF ) THEN
        DO 270 ilam = 1, NLAM_STORE
            LAM  = FILTOBS_LAMBDA(ilam,IFILT_OBS)
            FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) =
     &      FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS)

            FTRANSREF_STORE(ilam) = FTRANSSN_STORE(ilam)
270      CONTINUE  ! ILAM loop over original lambda binning
      ENDIF

      if ( USE_KCOR_REFACTOR ) then
         CALL LOAD_FILTERTRANS_CALIB(OPT_FRAME, IFILT_OBS, NLAM_STORE,
     &         FLAM_STORE, FTRANSSN_STORE )
      endif

c -----------------------------
      if ( UPD_DUMP ) then
        print*, '%%%% ', NLAM_STORE
        if (mod(NLAM_STORE,2).EQ.0) then
           ilam = NLAM_STORE/2
        else
         ilam = (NLAM_STORE+1)/2
        end if
        LAM  = FILTOBS_LAMBDA(ilam,IFILT_OBS)
        print*, 'xxxxx', NLAM_STORE
     &        , sngl(FTRANSSN_STORE(ilam))
     &        , sngl(FTRANSREF_STORE(ilam))

        print*, 'xxxx SN =' , CCID
        print*, 'xxxx LEXIST_REF =', LEXIST_REF
        print*, 'xxxx LEXIST_SN  =', LEXIST_SN
        print*, 'xxxx FILE_REF   =', FILTFILE_REF
        print*, 'xxxx FILE_SN    =', FILTFILE_SN

        print*, 'XXXXXX FILTER_UPDATE_EACHSN  DUMP end for ', CCID
        call flush(6)
      endif


      RETURN
      END   ! end FILTER_UPDATE_EACHSN_LEGACY


C =======================================
CDECK  ID>,  IMAP2FUPD. 
      INTEGER FUNCTION IMAP2_FUPDMATCH(CCID)

c Created May 19, 2012
c Search array IMAP2_FILTER_UPDATE_CCID(imap2)
c to find CCID match; return IMAP2 = index of array.
c Used to match CCID to sparse index associated
c with the filter-subdir.

      IMPLICIT NONE
      CHARACTER CCID*(*)  ! (I) SN name to match

c local  var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



      INTEGER IMAP2, L0, L1
      CHARACTER CCID_TMP*(MXCHAR_CCID), C1ERR*72, C2ERR*72

C ---------------- BEGIN ------------------

      IMAP2_FUPDMATCH = -9
      L0 = INDEX(CCID,' ') - 1

      DO 100 IMAP2 = 1, NMAP2_FILTER_UPDATE

         CCID_TMP  = MAP2_FILTER_UPDATE_CCID(IMAP2)
         L1 = INDEX(CCID_TMP // ' ',' ') - 1

         IF ( L0 .NE. L1 ) GOTO 100
         IF ( CCID(1:L0) .NE. CCID_TMP(1:L1) ) GOTO 100

c if we get here then return
         IMAP2_FUPDMATCH = IMAP2
         RETURN

100   CONTINUE


c if we get here then abort.
      write(c1err,61) CCID(1:8)
61    format('Could not find MAP2_FILTER_UPDATE match for CID=',A)
      c2err = 'Check FILTER.INFO file.'
      CALL MADABORT('IMAP2_FUPDMATCH', c1err, c2err )


      RETURN
      END

C ================================================
CDECK  ID>,  FUPD_SAME. 
      SUBROUTINE FILTER_UPDATE_SAMEFILT(ifilt)
      IMPLICIT NONE

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID


c +CDE,PARSECOM.

      INTEGER ifilt  ! (I) sparse SN & filter index

c local variables

      INTEGER ilam, NLAM, ifilt_obs

C ------------ BEGIN -------------

      ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
      NLAM      = NLAMBIN_FILTOBS(ifilt_obs)

      DO 100 ilam = 1, NLAM

          FILTOBS_TRANSSN_UPD(ilam,IFILT_OBS) =
     &    FILTOBS_TRANS(ilam,IFILT_OBS)

          FILTOBS_TRANSREF_UPD(ilam,IFILT_OBS) =
     &    FILTOBS_TRANS(ilam,IFILT_OBS)
100   CONTINUE

      RETURN
      END   ! end FILTER_UPDATE_SAMEFILT

C ==========================================
CDECK  ID>,  SETZPOFF. 
      SUBROUTINE SET_ZPOFF()
c
c Created July 17, 2011 by R.Kessler
c Called from RDKCOR to update MAGOBS_SHIFT_ZP_FILT(ifilt_obs)
c for each filter. Update based on FILTOBS_ZPOFF_SNPHOT(ifilt_obs)
c that is read either from the KCOR file or from the ZPOFF_FILE.
c
c Feb 22, 2012:
c  Use MAGOBS_SHIFT_ZP_USER(ifilt_obs)  so that final
c  SHIFT_ZP is OK even if RDKCOR is called multiple times.
c -------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFILECOM.  SNDATA_ROOT is here inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFILT, IFILT_OBS

C ------------- BEGIN -----------

c update ZP-shift for each filter (i.e., add to user-shift)
      DO ifilt  = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          MAGOBS_SHIFT_ZP_FILT(ifilt_obs) =
     &    MAGOBS_SHIFT_ZP_USER(ifilt_obs) +
     &    FILTOBS_ZPOFF_SNPHOT(ifilt_obs)
      ENDDO

c check for lambda-dependent MAGOBS_SHIFT (Sep 30, 2015)
      CALL MAGOBS_SHIFT_UPDATE()

c dump ZPOFF values vs. filter
      CALL DMP_ZPOFF

      RETURN
      END  ! end of SET_ZPOFF

C ==========================================
CDECK  ID>,  DMP_ZPOFF. 
      SUBROUTINE DMP_ZPOFF

c --------------------------
c Created Jul 17, 2011
c Dump zeropoint offsets to screen.
c
c Feb 2016: dump only obs-filters in kcor file; ingore un-defined filters.
c Nov 2022: separate filter loop over OBS and REST frame so that it works
c           for both legacy and refac kcor.
c
c -------------------------
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      REAL      ZPOFF_TOT
      INTEGER   ifilt_obs, ifilt_rest, ifilt
      character CFILT*2

C ------------------ BEGIN ------------

      print*,' '
      write(6,20) 'KCOR file'
20    format(T5,'Zeropoint offsets (ZPOFF) from : ', A)

      DO 100 ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         if ( ifilt_obs .EQ. IFILT_BESS_BX ) goto 100
         cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
         ZPOFF_TOT = MAGOBS_SHIFT_ZP_FILT(ifilt_obs)
         write(6,801) 'MAGOBS', cfilt(1:1), ZPOFF_TOT
100   CONTINUE

      DO 200 ifilt = 1, NFILTDEF_REST
         ifilt_rest = IFILTDEF_MAP_REST(ifilt)
         if ( ifilt_rest .EQ. IFILT_BESS_BX ) goto 200
         cfilt     = filtdef_string(ifilt_rest:ifilt_rest)
         ZPOFF_TOT = MAGREST_SHIFT_ZP_FILT(ifilt_rest)
         write(6,801) 'MAGREST', cfilt(1:1), ZPOFF_TOT
200   CONTINUE

801     format(T10,'Will apply net ',
     &     A,'_SHIFT_ZP(',A,') = ', F7.4 )

      CALL FLUSH(6)

      RETURN
      END  ! end of DMP_ZPOFF


C ======================================
CDECK  ID>,  FILTBTEST. 
      LOGICAL FUNCTION FILTBTEST(MSK8,ibit)
c Mar 29, 2011
C Return true if 1 <= IBIT < 90 is set in MSK8.
c Note that LSB=1 (not 0)
c

      INTEGER   IBIT    ! (I) bit to set
      INTEGER*8 MSK8(2) ! (I/O) 8-byte mask to set

      INTEGER IBIT2
      INTEGER MXBIT
      PARAMETER ( MXBIT =  60 )

      LOGICAL LTMP
C ------------ BEGIN ------------

      if ( IBIT .LE. MXBIT ) then
        LTMP = BTEST(MSK8(1),IBIT-1)
      else if ( IBIT .LT. 2*MXBIT ) then
        IBIT2  = IBIT-MXBIT
        LTMP   = BTEST(MSK8(2),IBIT2-1)
      endif
      FILTBTEST = LTMP
      RETURN
      END

C ======================================
CDECK  ID>,  FILTBSET. 
      SUBROUTINE FILTBSET(MSK8,ibit)
c Mar 29, 2011
C set bit IBIT(1 to 2*MXBIT) for long int MSK8.
c Note that the input argument is also the output
c with IBIT set.

      INTEGER   IBIT    ! (I) bit to set
      INTEGER*8 MSK8(2) ! (I/O) 8-byte mask to set

      INTEGER IBIT2
      INTEGER MXBIT
      PARAMETER ( MXBIT =  60 )

C ------------ BEGIN ------------

      if ( IBIT .LE. MXBIT ) then
        MSK8(1) = IBSET(MSK8(1),IBIT-1)
      else if ( IBIT .LT. 2*MXBIT ) then
        IBIT2   = IBIT-MXBIT
        MSK8(2) = IBSET(MSK8(2),IBIT2-1)
      endif

      RETURN
      END

C =======================================
CDECK  ID>,  MAGOBS_SHIFT_UPDATE. 
      SUBROUTINE MAGOBS_SHIFT_UPDATE()

c Created Sep 20 2015
c Loop over filters and apply optional shift-vs-lambda
c for ZP and PRIMARY mag. Allows coherent mag-shifts
c with just a few parameters instead of giving a mag
c shift for each band.
c See &SNLCINP parameters MAGOBS_SHIFT_[ZP,PRIMARY]_PARAMS(3)
c
      IMPLICIT NONE

c local


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFILT, IFILTDEF

      REAL MAGOBS_SHIFT_USRFUN  ! function
C --------------- BEGIN -----------

      DO ifilt = 1, NFILTDEF_SURVEY
         IFILTDEF = IFILTDEF_MAP_SURVEY(ifilt)

         magobs_shift_zp_filt(ifiltdef) =
     &   magobs_shift_zp_filt(ifiltdef) +
     &          MAGOBS_SHIFT_USRFUN(ifiltdef, 'ZP') ! Sep 2015

         magobs_shift_primary_filt(ifiltdef) =
     &   magobs_shift_primary_filt(ifiltdef) +
     &          MAGOBS_SHIFT_USRFUN(ifiltdef, 'PRIMARY') ! Sep 2015
      ENDDO

      RETURN
      END  ! end of MAGOBS_SHIFT_UPDATE

C =======================================
CDECK  ID>,  MAGOBS_SHIFT_USRFUN. 
      REAL FUNCTION MAGOBS_SHIFT_USRFUN(IFILTDEF, WHAT )

c Created Sep 30 2015
c Compute shift for what='ZP' or what='PRIMARY' for this IFILTDEF.
c Use SNLCINP parameters MAGOBS_SHIFT_[ZP,PRIMARY]_PARAMS to
c determine polynomial function of wavelength. This allows computing
c correlated systematics among filters using a function of wavelength
c so that you don't have to enter a shift for each band separately.
c
c BEWARE: POLYNOMIAL FUNCTION OF LAMBDA IN MICRONS (NOT ANGSTROMS)
c
c ----------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER    IFILTDEF   ! (I) absolute filter index
      CHARACTER  WHAT*(*)   ! (I) 'ZP' or 'PRIMARY'

c local var

      REAL LAM_um, SQLAM_um, COEF(0:2)
      CHARACTER FNAM*20

c ------------------- BEGIN ----------------

      FNAM = 'MAGOBS_SHIFT_USRFUN'
      MAGOBS_SHIFT_USRFUN = 0.0

      IF ( WHAT(1:2) .EQ. 'ZP' ) THEN
         COEF(0) = MAGOBS_SHIFT_ZP_PARAMS(1)
         COEF(1) = MAGOBS_SHIFT_ZP_PARAMS(2)
         COEF(2) = MAGOBS_SHIFT_ZP_PARAMS(3)
      ELSE IF ( WHAT(1:7) .EQ. 'PRIMARY' ) THEN
         COEF(0) = MAGOBS_SHIFT_PRIMARY_PARAMS(1)
         COEF(1) = MAGOBS_SHIFT_PRIMARY_PARAMS(2)
         COEF(2) = MAGOBS_SHIFT_PRIMARY_PARAMS(3)
      ELSE
         C1ERR = 'Invalid WHAT=' // WHAT
         C2ERR = 'for MAGOBS_SHIFT_XXX'
         CALL  MADABORT(FNAM, C1ERR, C2ERR)
      ENDIF

      LAM_um   = FILTOBS_LAMAVG(ifiltdef)/1.0E4
      SQLAM_um = LAM_um * LAM_um

      MAGOBS_SHIFT_USRFUN =
     &      COEF(0)
     &    + COEF(1) * LAM_um
     &    + COEF(2) * SQLAM_um

c xxxxxxxxxxxxxxxxx
c      write(6,66) WHAT(1:2), MAGOBS_SHIFT_USRFUN, IFILTDEF, LAM_um
c66    format(' xxx ', A2, ' = ', F7.4,' for IFILTDEF=',I3,
c     &      3x,'LAM=',F7.3,' um')
c      CALL FLUSH(6)
c xxxxxxxxxxxxxxxxx

      RETURN
      END  ! end of MAGOBS_SHIFT_USRFUN


C =======================================
CDECK  ID>,  FUPDINI. 
      SUBROUTINE FILTER_UPDATE_INIT(IERR)
c
c If FILTER_UPDATE_PATH is defined, read FILTER.INFO
c file for instructions on updating the filters for
c each SN.
c
c Jun 15 2016:  CALL ENVreplace(FILTER_UPDATE_PATH)
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY


c +CDE,PARSECOM.

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



      INTEGER IERR

c local var

      INTEGER
     &   LEN_UPDPATH, LEN_FULLPATH, L1, LEN_ROOT
     &  ,iwd, NWD, IERROPEN, ifilt, LWD0, LWD1

      character
     &   FILTINFO_FILE*(MXCHAR_FILENAME)
     &  ,NAME_forC*(MXCHAR_FILENAME)
     &  ,cwd*60, cwd_next*60, msg*100, FNAM*30

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C --------------- BEGIN -------------

      IERR = 0
      FNAM = 'FILTER_UPDATE_INIT'

      OPT_FILTER_UPDATE    = 0
      DO ifilt=1, MXFILT_ALL
        DOFLAG_FILTER_UPDATE(ifilt) = 0
      ENDDO

      PREFIX_UPD_TRANSSN  = ' '
      PREFIX_UPD_TRANSREF = ' '
      PREFIX_UPD_FILTDIR  = ' '
      SUFFIX_UPD_TRANSSN  = ' '
      SUFFIX_UPD_TRANSREF = ' '
      SUFFIX_UPD_FILTDIR  = ' '
      FILTINFO_UPD_SN     = .FALSE.
      FILTINFO_UPD_REF    = .FALSE.

      IF ( FILTER_UPDATE_PATH .EQ. ' ' ) RETURN

      CALL ENVreplace(FILTER_UPDATE_PATH)

      msg =
     &   "FILTER_UPDATE_INIT: Prepare SN-dependent Filter response"
      CALL PRBANNER(msg(1:60))

c -------------------------------------------------------
c first try $SNDATA_ROOT/filters/[FILTER_UPDATE_PATH]/
c if not there, then try absolute path.

      LEN_UPDPATH  = INDEX(FILTER_UPDATE_PATH,' ' ) -  1
      LEN_ROOT     = INDEX(SNDATA_ROOT,' ') - 1

      FILTER_UPDATE_TOPDIR = SNDATA_ROOT(1:LEN_ROOT)
     &    // '/filters/' // FILTER_UPDATE_PATH(1:LEN_UPDPATH)
      LEN_FULLPATH  = INDEX(FILTER_UPDATE_TOPDIR,' ') - 1


c check if/where FILTER.INFO exists ...
      FILTINFO_FILE = FILTER_UPDATE_TOPDIR(1:LEN_FULLPATH)
     &                 // '/FILTER.INFO'
      OPEN(UNIT=LUNTMP, FILE = FILTINFO_FILE,
     &     IOSTAT = IERROPEN, STATUS='OLD')
      IF ( IERROPEN .EQ. 0 ) THEN
        CLOSE(UNIT = LUNTMP)
      ELSE
c try absolute path
        LEN_FULLPATH = LEN_UPDPATH
        FILTER_UPDATE_TOPDIR  = FILTER_UPDATE_PATH
        FILTINFO_FILE = FILTER_UPDATE_PATH(1:LEN_UPDPATH)
     &           // '/FILTER.INFO'
      ENDIF

      L1 = INDEX(FILTINFO_FILE,' ') - 1
      print*,' Update Filter Response for each SN from : '
      print*,' ', FILTINFO_FILE(1:L1)

      NAME_forC = FILTINFO_FILE(1:L1)//char(0)
      NWD = STORE_PARSE_WORDS(MSKOPT_PARSE_WORDS_FILE,NAME_forC,
     &         FNAM//char(0), L1, 30 )


c parse enough to know which type of FILTER.INFO file we have;
c set global  OPT_FILTER_UPDATE and call PARSE1_XXX or PARSE2_XXX
c to do the appropriate parsing.

      DO 10 iwd = 1, min(1000,NWD)

          CALL get_PARSE_WORD_fortran(iwd+0, cwd,      LWD0 )
          CALL get_PARSE_WORD_fortran(iwd+1, cwd_next, LWD1 )

          if ( cwd .EQ. ' ' ) goto 10

          if ( CWD .EQ. 'FILTER_SUBDIR:' ) THEN
             CALL PARSE1_FILTER_INFO(NWD)
             OPT_FILTER_UPDATE  = OPT_FILTUPD_EACHSN
             RETURN
          ENDIF

          if ( CWD .EQ. 'FILTER_PATH:' ) THEN
             CALL PARSE2_FILTER_INFO(NWD)
             OPT_FILTER_UPDATE  = OPT_FILTUPD_MAP
             RETURN
          ENDIF

10    CONTINUE


c if we get here then abort.

      c1err = 'Cannot parse FILTER.INFO file'
      c2err = FILTER_UPDATE_TOPDIR(1:LEN_FULLPATH)
      CALL MADABORT("FILTER_UPDATE_INIT", c1err, c2err)

      RETURN
      END  ! end FILTER_UPDATE_INIT

C ======================================
CDECK  ID>,  PRS1FUPD. 
      SUBROUTINE PARSE1_FILTER_INFO(NWD)

c parse FILTER.INFO file that has a different filter set
c for each SN.

      IMPLICIT NONE

      INTEGER NWD ! (I) number of words in file

C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


c +CDE,PARSECOM.

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



      INTEGER IWD, istar, LEN

      character
     &   FILTER_SUBDIR*(MXCHAR_PATH)
     &  ,cwd*(MXCHAR_FILEWORD)
     &  ,cwd_next*(MXCHAR_FILEWORD)
     &  ,copt*(MXCHAR_FILEWORD)
     &  ,c1err*80, c2err*80

      LOGICAL LDUMP

C ----------- BEGIN ----------

      DO 10 iwd = 1, NWD-1

          CALL get_PARSE_WORD_fortran(iwd+0, cwd,      LEN)
          CALL get_PARSE_WORD_fortran(iwd+1, cwd_next, LEN)

          if ( cwd .EQ. ' ' ) goto 10

          if ( cwd .EQ. 'FILTER_SUBDIR:' ) then
            FILTER_SUBDIR = cwd_next
            istar = Index(FILTER_SUBDIR,'{SNID}')
            PREFIX_UPD_FILTDIR = FILTER_SUBDIR(1:istar-1)
            SUFFIX_UPD_FILTDIR = FILTER_SUBDIR(istar+6:99)
          endif

          if ( cwd .EQ. 'FILETRANS_SN:' ) then
            CALL SET_FILTINFO_UPD("SN", cwd_next)
          endif
          if ( cwd .EQ. 'FILETRANS_REF:' ) then
            CALL SET_FILTINFO_UPD("REF", cwd_next)
          endif

          if ( cwd(1:7) .EQ. 'OPTION:' ) then
             copt = cwd_next
             if ( copt(1:7) .EQ. 'DEFAULT' ) then

             else if ( copt(1:8) .EQ. 'SAMEFILT' ) then
               OPT_FILTER_UPDATE  = OPT_FILTUPD_SAMEFILT
             else
               C1ERR = 'Invalid FilterFile.INFO OPTION: ' // copt(1:20)
               C2ERR = 'Valid options: DEFAULT SAMEFILT '
               CALL MADABORT("FILTER_UPDATE_INIT", C1ERR, C2ERR )
             endif
          endif

10    CONTINUE

      LDUMP = .false.
      if ( LDUMP ) then
          print*, ' xxxxxx FILTER_SUBDIR= ', FILTER_SUBDIR(1:20)
          print*, ' xxxxxx   PREFIX_UPD_FILTDIR =',
     &                       PREFIX_UPD_FILTDIR(1:20)
          print*, ' xxxxxx   SUFFIX_UPD_FILTDIR =',
     &                       SUFFIX_UPD_FILTDIR(1:20)
      endif

      RETURN
      END

C ======================================
CDECK  ID>,  PRS2FUPD. 
      SUBROUTINE PARSE2_FILTER_INFO(NWD)

c Created July 16, 2011 by R.Kessler
c parse FILTER.INFO file that has a defined set of filters
c such as one set per SDSS-CCD column.
c IMAP is a sparse index 1-NMAP
c INDX is the absolute filter-path index in the FILTER.INFO file.
c
c Load MAP1_FILTER_UPDATE (subdir vs. index) and
c MAP2_FILTER_UPDATE (index vs. CCID)
c
c ------------------------

      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


c+CDE,PARSECOM.

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



      INTEGER NWD  ! (I) number of words to check

      INTEGER
     &   IWD, INDX, LEN
     &  ,IMAP1, IMAP1_STORE, NMAP1, NMAP2

      character
     &   cwd0*(MXCHAR_FILEWORD)
     &  ,cwd1*(MXCHAR_FILEWORD)
     &  ,cwd2*(MXCHAR_FILEWORD)
     &  ,ccid*(MXCHAR_CCID)
     &  ,c1err*80, c2err*80

C ---------------- BEGIN -------------

      NMAP1_FILTER_UPDATE = 0
      NMAP2_FILTER_UPDATE = 0

      NMAP1 = 0
      NMAP2 = 0

      DO 10 iwd = 1, NWD-2

          call get_PARSE_WORD_fortran(iwd+0, cwd0, LEN)
          call get_PARSE_WORD_fortran(iwd+1, cwd1, LEN)
          call get_PARSE_WORD_fortran(iwd+2, cwd2, LEN)

          if ( cwd0 .EQ. ' ' ) goto 10


          if ( cwd0 .EQ. 'FILTER_PATH:' ) then
             read(cwd1,*) INDX

             NMAP1 = NMAP1 + 1
             NMAP1_FILTER_UPDATE = NMAP1

             if ( NMAP1 .GT. MXMAP1_FILTER_UPDATE ) then
               write(c1err,1660) NMAP1, MXMAP1_FILTER_UPDATE
1660           format('NMAP=',I3,
     &           ' exceeds bound of MXMAP1_FILTER_UPDATE=',I3)
               c2err = 'Increase bound or reduce NMAP'
               CALL MADABORT('PARSE2_FILTER_INFO', C1ERR, C2ERR)
             endif
             MAP1_FILTER_UPDATE_INDX(NMAP1)    = INDX
             MAP1_FILTER_UPDATE_SUBDIR(NMAP1)  = CWD2
          endif

          if ( cwd0 .EQ. 'FILETRANS_SN:' ) then
            CALL SET_FILTINFO_UPD('SN', cwd1)
          endif
          if ( cwd0 .EQ. 'FILETRANS_REF:' ) then
            CALL SET_FILTINFO_UPD('REF', cwd1)
          endif



          if ( cwd0 .EQ. 'SN:' ) then
             CCID = cwd1(1:MXCHAR_CCID)
             read(cwd2,*) INDX

c translate INDX to sparse IMAP1
             IMAP1_STORE = -9
             DO imap1 = 1, NMAP1_FILTER_UPDATE
                if ( MAP1_FILTER_UPDATE_INDX(imap1) .EQ. INDX) then
                   imap1_store = imap1
                endif
             END DO

             if ( IMAP1_STORE .LE. 0 ) then
               write(c1err,670) INDX, CCID
               c2err = 'Check FILTER.INFO file.'
670            format('Undefined INDX=',I8,'   for  CID = ',A8)
               CALL MADABORT('PARSE2_FILTER_INFO', C1ERR, C2ERR)
             endif

c update 2nd map
             NMAP2 = NMAP2 + 1
             NMAP2_FILTER_UPDATE = NMAP2

             if ( NMAP2 .GT. MXSNLC_FILTUPD ) then
                write(c1err,661) MXSNLC_FILTUPD
661             format('MAP2 size exceeds bound of MXSNLC_FILTUPD=',I6)
                c2err = 'Check FILTER.INFO file.'
                CALL MADABORT("PARSE2_FILTER_INFO", C1ERR, C2ERR)
             endif

             MAP2_FILTER_UPDATE_CCID(NMAP2)    = CCID
             MAP2_FILTER_UPDATE_PTRMAP1(NMAP2) = IMAP1_STORE

          endif  !   'SN:' key


10    CONTINUE

c ---------------------------------------------------------

      write(6,60) NMAP1_FILTER_UPDATE
60    format(T4,'Found ',I2,' filter sets to use for updates.')

      write(6,61) NMAP2_FILTER_UPDATE
61    format(T4,'Filter update map stored for ',I6,' SNe.' )

      print*,' -------------------------------------------------- '

      RETURN
      END

C =================================
CDECK  ID>,  SETFUPD. 
      SUBROUTINE SET_FILTINFO_UPD(KEY,STRING)
c
c Created Jul 16, 2011
c
c Parse STRING for asterisk, and store PREFIX and SUFFIX
c before/after the asterisk. Used later to determine the
c name of the filter transmission  file where the  asterisk
c is replaced with the filter-character.
c
c Jul 5 2013: string-length fixes to avoid segfault in debug mode.
c             See use of LKEY and LSTR.
c
c ---------

      IMPLICIT  NONE

c input arguments
      CHARACTER KEY*(*)     ! (I) 'SN' or 'REF'
      CHARACTER STRING*(*)  ! (I) string to define filter filename

c local variables


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


c +CDE,PARSECOM.

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



      INTEGER istar, LSTR, LKEY
      LOGICAL LDUMP
C ------------ BEGIN -------------

      LSTR = INDEX(STRING,' ' ) - 1
      LKEY = INDEX(KEY//' ',   ' ' ) - 1

      istar = Index(STRING,'*')

      IF ( KEY(1:LKEY) .EQ. 'REF' ) THEN
          PREFIX_UPD_TRANSREF = STRING(1:istar-1)
          SUFFIX_UPD_TRANSREF = STRING(istar+1:LSTR)
          FILTINFO_UPD_REF = .TRUE.

      ELSE IF ( KEY(1:LKEY) .EQ. 'SN' ) THEN
          PREFIX_UPD_TRANSSN = STRING(1:istar-1)
          SUFFIX_UPD_TRANSSN = STRING(istar+1:LSTR)
          FILTINFO_UPD_SN = .TRUE.

      ELSE

      ENDIF

c print comment about filename syntax

      LDUMP = .TRUE.
      IF ( LDUMP ) THEN
         write(6,20) KEY, STRING(1:LSTR)
20       format(T4,'Filter-Trans filenames(', A, ') : ''',A,
     &          '''  with * => filter' )
      ENDIF

      RETURN
      END  ! end  SET_FILTINFO_UPD



C =======================
CDECK  ID>,  IN2DEX. 
      SUBROUTINE IN2DEX(IND,M,XX,YY,ZZ,XXM,YYM,SS,IER)
C-------------------------------
C Interface to 2d surface extrapolator.  This initializes the 2D
C extrapolator by interfacing to the surface fitter and storing
C the results. D. Cinabro May, 2006
C
C Usage:
C  IND (I) = Index of surface, INMAX allowed
C  M   (I) = number of data points (nx*ny)
C  XX  (I) = First Dimension inputs, double precision
C  YY  (I) = Second Dimension inputs, double precision
C  ZZ  (I) = Output of F(XX,YY) to be smoothed, double precision
C  XXM (I) = Range of X extrapolation min and max, double precision
C  YYM (I) = Range of Y extrapolation min and max, double precision
C  S   (I) = Smoothing parameter, double precision optimal value should be
C            bounded by (m-sqrt(2*m),m+sqrt(2m)).  See surfit documentation
C            for more advice.  Smaller means less smoothing.
C  IER (o) = Error flag.  <=0 is good, >0 is bad.  See surfit for meaning.
C
C Based on the DIERCKX package of Fortran subroutines for calculating
C smoothing splines for various kinds of data and geometries,
C with automatic knot selection.  This library is also called
C FITPACK, but is independent of the FITPACK library by Alan Cline.
C
C Reference:
C Paul Dierckx, Curve and Surface Fitting with Splines,
C Oxford University Press, 1993
C
C Developer
C Paul Dierckx, Department of Computer Science, K.U. Leuven,
C Celestijnenlaan 200 A,
C B-3001, Heverlee, Belgium Paul.Dierckx@cs.kuleuven.ac.be
C---------------------------------------------------------------
C
      IMPLICIT NONE
C
C User inputs
C
      INTEGER IOPT,M,IER
      REAL*8 XX(M),YY(M),ZZ(M),XXM(2),YYM(2),SS
C
C Surfit inputs
C
      INTEGER I, NXEST,NYEST
      REAL*8 X(M),Y(M),Z(M),W(M),XB,XE,YB,YE,S,EPS
C
C Surfit outputs in common block needed for function
C

C +CDE,DA2DEX. inserted below by ypatchy. 

C Data for surface smoother
C 5/02/2011 : INMAX=6 -> 8

      INTEGER IND,NMAX,NCMAX,INMAX
      PARAMETER (NMAX=4000, NCMAX=NMAX*100,INMAX=8)  ! save memory

cc      PARAMETER (NMAX=10000,NCMAX=NMAX*100,INMAX=20)  ! original

      INTEGER NX(INMAX),NY(INMAX),KX(INMAX),KY(INMAX)
      INTEGER NND,JND(INMAX)
      REAL*8 TX(NMAX,INMAX),TY(NMAX,INMAX), C(NCMAX,INMAX)
      REAL*8 WRK1(NCMAX,INMAX)
      COMMON /DA2DEX/ TX,NX,TY,NY,C,WRK1,KX,KY,NND,JND


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST

C
      LOGICAL FIRST, USEY
      DATA FIRST/.TRUE./
      INTEGER IN
C
C Working arrays
C
      INTEGER IWRK(NMAX),LWRK1,LWRK2,KWRK
      REAL*8 FP,WRK2(NCMAX)
C
C--------------------------
C
      IF (FIRST) THEN
        FIRST = .FALSE.
        NND = 0
      ENDIF
C
      IN = 0
      IF (NND.GT.0) THEN
        DO 50 I = 1,NND
          IF (IND.EQ.JND(I)) THEN
            IN = I
          ENDIF
  50    CONTINUE
      ENDIF
      IF (IN.EQ.0) THEN
        NND = NND + 1
        JND(NND) = IND
        IN = NND
      ENDIF

      IF (IN.GT.INMAX) THEN
        print*,' '
        print*,' IN2DEX Warning: IND =',IND
        print*,' Too many functions defined.  Increase INMAX '
        print*,' ***** ABORT ***** '
        CALL EXIT(EXIT_ERRCODE)
      ENDIF

C Tell the fitter to not use a user supplied set of knots
      IOPT = 1
      USEY = .FALSE.
      DO 100 I = 1,M
        X(I) = XX(I)
        Y(I) = YY(I)
        Z(I) = ZZ(I)
C All points wieghted equally
        W(I) = 1.0
        if ( Y(I) .NE. Y(1) ) USEY = .TRUE.
 100  CONTINUE
      XB = XXM(1)
      XE = XXM(2)
      YB = YYM(1)
      YE = YYM(2)
C Use cublic splines.  Cannot be larger than 5.
      KX(IN) = 3

      IF ( USEY ) then
         KY(IN) = 3
      ELSE
         KY(IN) = 1
      ENDIF

      S = SS
C Maximum Number of knots.  Value here is advice from surfit plus 10
      NXEST = KX(IN) + 1 + NINT(SQRT(REAL(M)/2.0))  + 10
      NYEST = KY(IN) + 1 + NINT(SQRT(REAL(M)/2.0))  + 10
C Nearness of fit parameter, 1/10000 should be more than adequate
      EPS = 0.0001
      LWRK1 = NCMAX
      LWRK2 = NCMAX
      KWRK = NMAX
C Zero out the working array to avoid hysterisis
      DO 101 I = 1,NCMAX
        WRK1(I,IN) = 0.0
 101  CONTINUE
C
C Call the fitter
C
      CALL SURFIT(IOPT,M,X,Y,Z,W,XB,XE,YB,YE,KX(IN),KY(IN),
     &  S,NXEST,NYEST,NMAX,EPS,NX(IN),TX(1,IN),NY(IN),TY(1,IN),
     &  C(1,IN),FP,WRK1(1,IN),LWRK1,WRK2,LWRK2,IWRK,KWRK,IER)
C
      RETURN
      END

CDECK  ID>,  GE2DEDX. 
      DOUBLE PRECISION FUNCTION GE2DEX(IND,XX1,YY1,IER)
C----------------------------------------------------
C GE2DEX gets the result of the smoothing initialized by IN2DEX
C
C GE2DEX(XX1,YY1,IER)
C  IND  (I) = Index of function, INMAX allowed
C  XX1  (I) = First Dimension input, double precision
C  YY1  (I) = Second Dimension inputs, double precision
C  IER  (o) = Error flag.  =0 is good, =10 is bad.  See bispev for meaning.
C---------------------------------------------------------
      IMPLICIT NONE
      REAL*8 XX1(1),YY1(1)
      INTEGER IER
      REAL*8 X1(1),Y1(1),Z1(1)
C
C Stuff from the fit
C

C +CDE,DA2DEX. inserted below by ypatchy. 

C Data for surface smoother
C 5/02/2011 : INMAX=6 -> 8

      INTEGER IND,NMAX,NCMAX,INMAX
      PARAMETER (NMAX=4000, NCMAX=NMAX*100,INMAX=8)  ! save memory

cc      PARAMETER (NMAX=10000,NCMAX=NMAX*100,INMAX=20)  ! original

      INTEGER NX(INMAX),NY(INMAX),KX(INMAX),KY(INMAX)
      INTEGER NND,JND(INMAX)
      REAL*8 TX(NMAX,INMAX),TY(NMAX,INMAX), C(NCMAX,INMAX)
      REAL*8 WRK1(NCMAX,INMAX)
      COMMON /DA2DEX/ TX,NX,TY,NY,C,WRK1,KX,KY,NND,JND


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST

C
C Working arrays
C
      INTEGER IWRK(NMAX),LWRK1,KWRK,IX,IY,IN,I
C---------------------------------------------------------
C Get the right index
      IN = 0
      DO 50 I = 1,NND
        IF (IND.EQ.JND(I)) THEN
          IN = I
        ENDIF
  50  CONTINUE
      IF (IN.EQ.0) THEN
        print*,' '
        print*,' GE2DEX Warning: IND =',IND
        print*,' Unrecognized function index? '
        print*,' ***** ABORT ***** '
        CALL EXIT(EXIT_ERRCODE)
      ENDIF

C Evaluate the spline at XX1, YY1

      X1(1) = XX1(1)
      Y1(1) = YY1(1)
      LWRK1 = NCMAX
      KWRK = NMAX
      IX = 1
      IY = 1
      CALL BISPEV(TX(1,IN),NX(IN),TY(1,IN),NY(IN),C(1,IN),
     &  KX(IN),KY(IN),X1,IX,Y1,IY,Z1,WRK1(1,IN),LWRK1,IWRK,KWRK,IER)
      GE2DEX = Z1(1)
C
      RETURN
      END
C =============================
CDECK  ID>,  UTILEX. 
      subroutine surfit(iopt,m,x,y,z,w,xb,xe,yb,ye,kx,ky,s,nxest,nyest,
     *  nmax,eps,nx,tx,ny,ty,c,fp,wrk1,lwrk1,wrk2,lwrk2,iwrk,kwrk,ier)
c given the set of data points (x(i),y(i),z(i)) and the set of positive
c numbers w(i),i=1,...,m, subroutine surfit determines a smooth bivar-
c iate spline approximation s(x,y) of degrees kx and ky on the rect-
c angle xb <= x <= xe, yb <= y <= ye.
c if iopt = -1 surfit calculates the weighted least-squares spline
c according to a given set of knots.
c if iopt >= 0 the total numbers nx and ny of these knots and their
c position tx(j),j=1,...,nx and ty(j),j=1,...,ny are chosen automatic-
c ally by the routine. the smoothness of s(x,y) is then achieved by
c minimalizing the discontinuity jumps in the derivatives of s(x,y)
c across the boundaries of the subpanels (tx(i),tx(i+1))*(ty(j),ty(j+1).
c the amounth of smoothness is determined by the condition that f(p) =
c sum ((w(i)*(z(i)-s(x(i),y(i))))**2) be <= s, with s a given non-neg-
c ative constant, called the smoothing factor.
c the fit is given in the b-spline representation (b-spline coefficients
c c((ny-ky-1)*(i-1)+j),i=1,...,nx-kx-1;j=1,...,ny-ky-1) and can be eval-
c uated by means of subroutine bispev.
c
c calling sequence:
c     call surfit(iopt,m,x,y,z,w,xb,xe,yb,ye,kx,ky,s,nxest,nyest,
c    *  nmax,eps,nx,tx,ny,ty,c,fp,wrk1,lwrk1,wrk2,lwrk2,iwrk,kwrk,ier)
c
c parameters:
c  iopt  : integer flag. on entry iopt must specify whether a weighted
c          least-squares spline (iopt=-1) or a smoothing spline (iopt=0
c          or 1) must be determined.
c          if iopt=0 the routine will start with an initial set of knots
c          tx(i)=xb,tx(i+kx+1)=xe,i=1,...,kx+1;ty(i)=yb,ty(i+ky+1)=ye,i=
c          1,...,ky+1. if iopt=1 the routine will continue with the set
c          of knots found at the last call of the routine.
c          attention: a call with iopt=1 must always be immediately pre-
c                     ceded by another call with iopt=1 or iopt=0.
c          unchanged on exit.
c  m     : integer. on entry m must specify the number of data points.
c          m >= (kx+1)*(ky+1). unchanged on exit.
c  x     : real array of dimension at least (m).
c  y     : real array of dimension at least (m).
c  z     : real array of dimension at least (m).
c          before entry, x(i),y(i),z(i) must be set to the co-ordinates
c          of the i-th data point, for i=1,...,m. the order of the data
c          points is immaterial. unchanged on exit.
c  w     : real array of dimension at least (m). before entry, w(i) must
c          be set to the i-th value in the set of weights. the w(i) must
c          be strictly positive. unchanged on exit.
c  xb,xe : real values. on entry xb,xe,yb and ye must specify the bound-
c  yb,ye   aries of the rectangular approximation domain.
c          xb<=x(i)<=xe,yb<=y(i)<=ye,i=1,...,m. unchanged on exit.
c  kx,ky : integer values. on entry kx and ky must specify the degrees
c          of the spline. 1<=kx,ky<=5. it is recommended to use bicubic
c          (kx=ky=3) splines. unchanged on exit.
c  s     : real. on entry (in case iopt>=0) s must specify the smoothing
c          factor. s >=0. unchanged on exit.
c          for advice on the choice of s see further comments
c  nxest : integer. unchanged on exit.
c  nyest : integer. unchanged on exit.
c          on entry, nxest and nyest must specify an upper bound for the
c          number of knots required in the x- and y-directions respect.
c          these numbers will also determine the storage space needed by
c          the routine. nxest >= 2*(kx+1), nyest >= 2*(ky+1).
c          in most practical situation nxest = kx+1+sqrt(m/2), nyest =
c          ky+1+sqrt(m/2) will be sufficient. see also further comments.
c  nmax  : integer. on entry nmax must specify the actual dimension of
c          the arrays tx and ty. nmax >= nxest, nmax >=nyest.
c          unchanged on exit.
c  eps   : real.
c          on entry, eps must specify a threshold for determining the
c          effective rank of an over-determined linear system of equat-
c          ions. 0 < eps < 1.  if the number of decimal digits in the
c          computer representation of a real number is q, then 10**(-q)
c          is a suitable value for eps in most practical applications.
c          unchanged on exit.
c  nx    : integer.
c          unless ier=10 (in case iopt >=0), nx will contain the total
c          number of knots with respect to the x-variable, of the spline
c          approximation returned. if the computation mode iopt=1 is
c          used, the value of nx should be left unchanged between sub-
c          sequent calls.
c          in case iopt=-1, the value of nx should be specified on entry
c  tx    : real array of dimension nmax.
c          on succesful exit, this array will contain the knots of the
c          spline with respect to the x-variable, i.e. the position of
c          the interior knots tx(kx+2),...,tx(nx-kx-1) as well as the
c          position of the additional knots tx(1)=...=tx(kx+1)=xb and
c          tx(nx-kx)=...=tx(nx)=xe needed for the b-spline representat.
c          if the computation mode iopt=1 is used, the values of tx(1),
c          ...,tx(nx) should be left unchanged between subsequent calls.
c          if the computation mode iopt=-1 is used, the values tx(kx+2),
c          ...tx(nx-kx-1) must be supplied by the user, before entry.
c          see also the restrictions (ier=10).
c  ny    : integer.
c          unless ier=10 (in case iopt >=0), ny will contain the total
c          number of knots with respect to the y-variable, of the spline
c          approximation returned. if the computation mode iopt=1 is
c          used, the value of ny should be left unchanged between sub-
c          sequent calls.
c          in case iopt=-1, the value of ny should be specified on entry
c  ty    : real array of dimension nmax.
c          on succesful exit, this array will contain the knots of the
c          spline with respect to the y-variable, i.e. the position of
c          the interior knots ty(ky+2),...,ty(ny-ky-1) as well as the
c          position of the additional knots ty(1)=...=ty(ky+1)=yb and
c          ty(ny-ky)=...=ty(ny)=ye needed for the b-spline representat.
c          if the computation mode iopt=1 is used, the values of ty(1),
c          ...,ty(ny) should be left unchanged between subsequent calls.
c          if the computation mode iopt=-1 is used, the values ty(ky+2),
c          ...ty(ny-ky-1) must be supplied by the user, before entry.
c          see also the restrictions (ier=10).
c  c     : real array of dimension at least (nxest-kx-1)*(nyest-ky-1).
c          on succesful exit, c contains the coefficients of the spline
c          approximation s(x,y)
c  fp    : real. unless ier=10, fp contains the weighted sum of
c          squared residuals of the spline approximation returned.
c  wrk1  : real array of dimension (lwrk1). used as workspace.
c          if the computation mode iopt=1 is used the value of wrk1(1)
c          should be left unchanged between subsequent calls.
c          on exit wrk1(2),wrk1(3),...,wrk1(1+(nx-kx-1)*(ny-ky-1)) will
c          contain the values d(i)/max(d(i)),i=1,...,(nx-kx-1)*(ny-ky-1)
c          with d(i) the i-th diagonal element of the reduced triangular
c          matrix for calculating the b-spline coefficients. it includes
c          those elements whose square is less than eps,which are treat-
c          ed as 0 in the case of presumed rank deficiency (ier<-2).
c  lwrk1 : integer. on entry lwrk1 must specify the actual dimension of
c          the array wrk1 as declared in the calling (sub)program.
c          lwrk1 must not be too small. let
c            u = nxest-kx-1, v = nyest-ky-1, km = max(kx,ky)+1,
c            ne = max(nxest,nyest), bx = kx*v+ky+1, by = ky*u+kx+1,
c            if(bx.le.by) b1 = bx, b2 = b1+v-ky
c            if(bx.gt.by) b1 = by, b2 = b1+u-kx  then
c          lwrk1 >= u*v*(2+b1+b2)+2*(u+v+km*(m+ne)+ne-kx-ky)+b2+1
c  wrk2  : real array of dimension (lwrk2). used as workspace, but
c          only in the case a rank deficient system is encountered.
c  lwrk2 : integer. on entry lwrk2 must specify the actual dimension of
c          the array wrk2 as declared in the calling (sub)program.
c          lwrk2 > 0 . a save upper boundfor lwrk2 = u*v*(b2+1)+b2
c          where u,v and b2 are as above. if there are enough data
c          points, scattered uniformly over the approximation domain
c          and if the smoothing factor s is not too small, there is a
c          good chance that this extra workspace is not needed. a lot
c          of memory might therefore be saved by setting lwrk2=1.
c          (see also ier > 10)
c  iwrk  : integer array of dimension (kwrk). used as workspace.
c  kwrk  : integer. on entry kwrk must specify the actual dimension of
c          the array iwrk as declared in the calling (sub)program.
c          kwrk >= m+(nxest-2*kx-1)*(nyest-2*ky-1).
c  ier   : integer. unless the routine detects an error, ier contains a
c          non-positive value on exit, i.e.
c   ier=0  : normal return. the spline returned has a residual sum of
c            squares fp such that abs(fp-s)/s <= tol with tol a relat-
c            ive tolerance set to 0.001 by the program.
c   ier=-1 : normal return. the spline returned is an interpolating
c            spline (fp=0).
c   ier=-2 : normal return. the spline returned is the weighted least-
c            squares polynomial of degrees kx and ky. in this extreme
c            case fp gives the upper bound for the smoothing factor s.
c   ier<-2 : warning. the coefficients of the spline returned have been
c            computed as the minimal norm least-squares solution of a
c            (numerically) rank deficient system. (-ier) gives the rank.
c            especially if the rank deficiency which can be computed as
c            (nx-kx-1)*(ny-ky-1)+ier, is large the results may be inac-
c            curate. they could also seriously depend on the value of
c            eps.
c   ier=1  : error. the required storage space exceeds the available
c            storage space, as specified by the parameters nxest and
c            nyest.
c            probably causes : nxest or nyest too small. if these param-
c            eters are already large, it may also indicate that s is
c            too small
c            the approximation returned is the weighted least-squares
c            spline according to the current set of knots.
c            the parameter fp gives the corresponding weighted sum of
c            squared residuals (fp>s).
c   ier=2  : error. a theoretically impossible result was found during
c            the iteration proces for finding a smoothing spline with
c            fp = s. probably causes : s too small or badly chosen eps.
c            there is an approximation returned but the corresponding
c            weighted sum of squared residuals does not satisfy the
c            condition abs(fp-s)/s < tol.
c   ier=3  : error. the maximal number of iterations maxit (set to 20
c            by the program) allowed for finding a smoothing spline
c            with fp=s has been reached. probably causes : s too small
c            there is an approximation returned but the corresponding
c            weighted sum of squared residuals does not satisfy the
c            condition abs(fp-s)/s < tol.
c   ier=4  : error. no more knots can be added because the number of
c            b-spline coefficients (nx-kx-1)*(ny-ky-1) already exceeds
c            the number of data points m.
c            probably causes : either s or m too small.
c            the approximation returned is the weighted least-squares
c            spline according to the current set of knots.
c            the parameter fp gives the corresponding weighted sum of
c            squared residuals (fp>s).
c   ier=5  : error. no more knots can be added because the additional
c            knot would (quasi) coincide with an old one.
c            probably causes : s too small or too large a weight to an
c            inaccurate data point.
c            the approximation returned is the weighted least-squares
c            spline according to the current set of knots.
c            the parameter fp gives the corresponding weighted sum of
c            squared residuals (fp>s).
c   ier=10 : error. on entry, the input data are controlled on validity
c            the following restrictions must be satisfied.
c            -1<=iopt<=1, 1<=kx,ky<=5, m>=(kx+1)*(ky+1), nxest>=2*kx+2,
c            nyest>=2*ky+2, 0<eps<1, nmax>=nxest, nmax>=nyest,
c            xb<=x(i)<=xe, yb<=y(i)<=ye, w(i)>0, i=1,...,m
c            lwrk1 >= u*v*(2+b1+b2)+2*(u+v+km*(m+ne)+ne-kx-ky)+b2+1
c            kwrk >= m+(nxest-2*kx-1)*(nyest-2*ky-1)
c            if iopt=-1: 2*kx+2<=nx<=nxest
c                        xb<tx(kx+2)<tx(kx+3)<...<tx(nx-kx-1)<xe
c                        2*ky+2<=ny<=nyest
c                        yb<ty(ky+2)<ty(ky+3)<...<ty(ny-ky-1)<ye
c            if iopt>=0: s>=0
c            if one of these conditions is found to be violated,control
c            is immediately repassed to the calling program. in that
c            case there is no approximation returned.
c   ier>10 : error. lwrk2 is too small, i.e. there is not enough work-
c            space for computing the minimal least-squares solution of
c            a rank deficient system of linear equations. ier gives the
c            requested value for lwrk2. there is no approximation re-
c            turned but, having saved the information contained in nx,
c            ny,tx,ty,wrk1, and having adjusted the value of lwrk2 and
c            the dimension of the array wrk2 accordingly, the user can
c            continue at the point the program was left, by calling
c            surfit with iopt=1.
c
c further comments:
c  by means of the parameter s, the user can control the tradeoff
c   between closeness of fit and smoothness of fit of the approximation.
c   if s is too large, the spline will be too smooth and signal will be
c   lost ; if s is too small the spline will pick up too much noise. in
c   the extreme cases the program will return an interpolating spline if
c   s=0 and the weighted least-squares polynomial (degrees kx,ky)if s is
c   very large. between these extremes, a properly chosen s will result
c   in a good compromise between closeness of fit and smoothness of fit.
c   to decide whether an approximation, corresponding to a certain s is
c   satisfactory the user is highly recommended to inspect the fits
c   graphically.
c   recommended values for s depend on the weights w(i). if these are
c   taken as 1/d(i) with d(i) an estimate of the standard deviation of
c   z(i), a good s-value should be found in the range (m-sqrt(2*m),m+
c   sqrt(2*m)). if nothing is known about the statistical error in z(i)
c   each w(i) can be set equal to one and s determined by trial and
c   error, taking account of the comments above. the best is then to
c   start with a very large value of s ( to determine the least-squares
c   polynomial and the corresponding upper bound fp0 for s) and then to
c   progressively decrease the value of s ( say by a factor 10 in the
c   beginning, i.e. s=fp0/10, fp0/100,...and more carefully as the
c   approximation shows more detail) to obtain closer fits.
c   to choose s very small is strongly discouraged. this considerably
c   increases computation time and memory requirements. it may also
c   cause rank-deficiency (ier<-2) and endager numerical stability.
c   to economize the search for a good s-value the program provides with
c   different modes of computation. at the first call of the routine, or
c   whenever he wants to restart with the initial set of knots the user
c   must set iopt=0.
c   if iopt=1 the program will continue with the set of knots found at
c   the last call of the routine. this will save a lot of computation
c   time if surfit is called repeatedly for different values of s.
c   the number of knots of the spline returned and their location will
c   depend on the value of s and on the complexity of the shape of the
c   function underlying the data. if the computation mode iopt=1
c   is used, the knots returned may also depend on the s-values at
c   previous calls (if these were smaller). therefore, if after a number
c   of trials with different s-values and iopt=1, the user can finally
c   accept a fit as satisfactory, it may be worthwhile for him to call
c   surfit once more with the selected value for s but now with iopt=0.
c   indeed, surfit may then return an approximation of the same quality
c   of fit but with fewer knots and therefore better if data reduction
c   is also an important objective for the user.
c   the number of knots may also depend on the upper bounds nxest and
c   nyest. indeed, if at a certain stage in surfit the number of knots
c   in one direction (say nx) has reached the value of its upper bound
c   (nxest), then from that moment on all subsequent knots are added
c   in the other (y) direction. this may indicate that the value of
c   nxest is too small. on the other hand, it gives the user the option
c   of limiting the number of knots the routine locates in any direction
c   for example, by setting nxest=2*kx+2 (the lowest allowable value for
c   nxest), the user can indicate that he wants an approximation which
c   is a simple polynomial of degree kx in the variable x.
c
c  other subroutines required:
c    fpback,fpbspl,fpsurf,fpdisc,fpgivs,fprank,fprati,fprota,fporde
c
c  references:
c   dierckx p. : an algorithm for surface fitting with spline functions
c                ima j. numer. anal. 1 (1981) 267-283.
c   dierckx p. : an algorithm for surface fitting with spline functions
c                report tw50, dept. computer science,k.u.leuven, 1980.
c   dierckx p. : curve and surface fitting with splines, monographs on
c                numerical analysis, oxford university press, 1993.
c
c  author:
c    p.dierckx
c    dept. computer science, k.u. leuven
c    celestijnenlaan 200a, b-3001 heverlee, belgium.
c    e-mail : Paul.Dierckx@cs.kuleuven.ac.be
c
c  creation date : may 1979
c  latest update : march 1987
c
c  ..

      IMPLICIT NONE

c  ..scalar arguments..
      real*8 xb,xe,yb,ye,s,eps,fp
      integer iopt,m,kx,ky,nxest,nyest,nmax,nx,ny,lwrk1,lwrk2,kwrk,ier
c  ..array arguments..
      real*8 x(m),y(m),z(m),w(m),tx(nmax),ty(nmax),
     * c((nxest-kx-1)*(nyest-ky-1)),wrk1(lwrk1),wrk2(lwrk2)
      integer iwrk(kwrk)
c  ..local scalars..
      real*8 tol
      integer i,ib1,ib3,jb1,ki,kmax,km1,km2,kn,kwest,kx1,ky1,la,lbx,
     * lby,lco,lf,lff,lfp,lh,lq,lsx,lsy,lwest,maxit,ncest,nest,nek,
     * nminx,nminy,nmx,nmy,nreg,nrint,nxk,nyk
c  ..function references..
      integer max0
c  ..subroutine references..
c    fpsurf
c  ..

c  we set up the parameters tol and maxit.
      maxit = 20
      tol = 0.1e-02
c  before starting computations a data check is made. if the input data
c  are invalid,control is immediately repassed to the calling program.
      ier = 10
      if(eps.le.0. .or. eps.ge.1.) go to 70
      if(kx.le.0 .or. kx.gt.5) go to 70
      kx1 = kx+1
      if(ky.le.0 .or. ky.gt.5) go to 70
      ky1 = ky+1
      kmax = max0(kx,ky)
      km1 = kmax+1
      km2 = km1+1
      if(iopt.lt.(-1) .or. iopt.gt.1) go to 70
      if(m.lt.(kx1*ky1)) go to 70
      nminx = 2*kx1
      if(nxest.lt.nminx .or. nxest.gt.nmax) go to 70
      nminy = 2*ky1
      if(nyest.lt.nminy .or. nyest.gt.nmax) go to 70
      nest = max0(nxest,nyest)
      nxk = nxest-kx1
      nyk = nyest-ky1
      ncest = nxk*nyk
      nmx = nxest-nminx+1
      nmy = nyest-nminy+1
      nrint = nmx+nmy
      nreg = nmx*nmy
      ib1 = kx*nyk+ky1
      jb1 = ky*nxk+kx1
      ib3 = kx1*nyk+1
      if(ib1.le.jb1) go to 10
      ib1 = jb1
      ib3 = ky1*nxk+1
  10  lwest = ncest*(2+ib1+ib3)+2*(nrint+nest*km2+m*km1)+ib3
      kwest = m+nreg
      if(lwrk1.lt.lwest .or. kwrk.lt.kwest) go to 70
      if(xb.ge.xe .or. yb.ge.ye) go to 70
      do 20 i=1,m
        if(w(i).le.0.) go to 70
        if(x(i).lt.xb .or. x(i).gt.xe) go to 70
        if(y(i).lt.yb .or. y(i).gt.ye) go to 70
  20  continue
      if(iopt.ge.0) go to 50
      if(nx.lt.nminx .or. nx.gt.nxest) go to 70
      nxk = nx-kx1
      tx(kx1) = xb
      tx(nxk+1) = xe
      do 30 i=kx1,nxk
        if(tx(i+1).le.tx(i)) go to 70
  30  continue
      if(ny.lt.nminy .or. ny.gt.nyest) go to 70
      nyk = ny-ky1
      ty(ky1) = yb
      ty(nyk+1) = ye
      do 40 i=ky1,nyk
        if(ty(i+1).le.ty(i)) go to 70
  40  continue
      go to 60
  50  if(s.lt.0.) go to 70
  60  ier = 0
c  we partition the working space and determine the spline approximation
      kn = 1
      ki = kn+m
      lq = 2
      la = lq+ncest*ib3
      lf = la+ncest*ib1
      lff = lf+ncest
      lfp = lff+ncest
      lco = lfp+nrint
      lh = lco+nrint
      lbx = lh+ib3
      nek = nest*km2
      lby = lbx+nek
      lsx = lby+nek
      lsy = lsx+m*km1
      call fpsurf(iopt,m,x,y,z,w,xb,xe,yb,ye,kx,ky,s,nxest,nyest,
     * eps,tol,maxit,nest,km1,km2,ib1,ib3,ncest,nrint,nreg,nx,tx,
     * ny,ty,c,fp,wrk1(1),wrk1(lfp),wrk1(lco),wrk1(lf),wrk1(lff),
     * wrk1(la),wrk1(lq),wrk1(lbx),wrk1(lby),wrk1(lsx),wrk1(lsy),
     * wrk1(lh),iwrk(ki),iwrk(kn),wrk2,lwrk2,ier)
  70  return
      end

      subroutine fpback(a,z,n,k,c,nest)
      IMPLICIT NONE

c  subroutine fpback calculates the solution of the system of
c  equations a*c = z with a a n x n upper triangular matrix
c  of bandwidth k.
c  ..
c  ..scalar arguments..
      integer n,k,nest
c  ..array arguments..
      real*8 a(nest,k),z(n),c(n)
c  ..local scalars..
      real*8 store
      integer i,i1,j,k1,l,m
c  ..
      k1 = k-1
      c(n) = z(n)/a(n,1)
      i = n-1
      if(i.eq.0) go to 30
      do 20 j=2,n
        store = z(i)
        i1 = k1
        if(j.le.k1) i1 = j-1
        m = i
        do 10 l=1,i1
          m = m+1
          store = store-c(m)*a(i,l+1)
  10    continue
        c(i) = store/a(i,1)
        i = i-1
  20  continue
  30  return
      end

      subroutine fpbspl(t,n,k,x,l,h)
      IMPLICIT NONE
c  subroutine fpbspl evaluates the (k+1) non-zero b-splines of
c  degree k at t(l) <= x < t(l+1) using the stable recurrence
c  relation of de boor and cox.
c  ..
c  ..scalar arguments..
      real*8 x
      integer n,k,l
c  ..array arguments..
      real*8 t(n),h(6)
c  ..local scalars..
      real*8 f,one
      integer i,j,li,lj
c  ..local arrays..
      real*8 hh(5)
c  ..
      one = 0.1e+01
      h(1) = one
      do 20 j=1,k
        do 10 i=1,j
          hh(i) = h(i)
  10    continue
        h(1) = 0.
        do 21 i=1,j
          li = l+i
          lj = li-j
          f = hh(i)/(t(li)-t(lj))
          h(i) = h(i)+f*(t(li)-x)
          h(i+1) = f*(x-t(lj))
  21  continue
  20  continue
      return
      end

      subroutine fpsurf(iopt,m,x,y,z,w,xb,xe,yb,ye,kxx,kyy,s,nxest,
     * nyest,eta,tol,maxit,nmax,km1,km2,ib1,ib3,nc,intest,nrest,
     * nx0,tx,ny0,ty,c,fp,fp0,fpint,coord,f,ff,a,q,bx,by,spx,spy,h,
     * index,nummer,wrk,lwrk,ier)
      IMPLICIT NONE

c  ..
c  ..scalar arguments..
      real*8 xb,xe,yb,ye,s,eta,tol,fp,fp0
      integer iopt,m,kxx,kyy,nxest,nyest,maxit,nmax,km1,km2,ib1,ib3,
     * nc,intest,nrest,nx0,ny0,lwrk,ier
c  ..array arguments..
      real*8 x(m),y(m),z(m),w(m),tx(nmax),ty(nmax),c(nc),fpint(intest),
     * coord(intest),f(nc),ff(nc),a(nc,ib1),q(nc,ib3),bx(nmax,km2),
     * by(nmax,km2),spx(m,km1),spy(m,km1),h(ib3),wrk(lwrk)
      integer index(nrest),nummer(m)
c  ..local scalars..
      real*8 acc,arg,cos,dmax,fac1,fac2,fpmax,fpms,f1,f2,f3,hxi,p,pinv,
     * piv,p1,p2,p3,sigma,sin,sq,store,wi,x0,x1,y0,y1,zi,eps,
     * rn,one,con1,con9,con4,half,ten
      integer i,iband,iband1,iband3,iband4,ibb,ichang,ich1,ich3,ii,
     * in,irot,iter,i1,i2,i3,j,jrot,jxy,j1,kx,kx1,kx2,ky,ky1,ky2,l,
     * la,lf,lh,lwest,lx,ly,l1,l2,n,ncof,nk1x,nk1y,nminx,nminy,nreg,
     * nrint,num,num1,nx,nxe,nxx,ny,nye,nyy,n1,rank
c  ..local arrays..
      real*8 hx(6),hy(6)
cc      real*8 dif  ! for computed goto
c  ..function references..
      real*8 abs,fprati,sqrt
      integer min0
c  ..subroutine references..
c    fpback,fpbspl,fpgivs,fpdisc,fporde,fprank,fprota
c  ..
c  set constants
      one = 0.1e+01
      con1 = 0.1e0
      con9 = 0.9e0
      con4 = 0.4e-01
      half = 0.5e0
      ten = 0.1e+02
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c part 1: determination of the number of knots and their position.     c
c ****************************************************************     c
c given a set of knots we compute the least-squares spline sinf(x,y),  c
c and the corresponding weighted sum of squared residuals fp=f(p=inf). c
c if iopt=-1  sinf(x,y) is the requested approximation.                c
c if iopt=0 or iopt=1 we check whether we can accept the knots:        c
c   if fp <=s we will continue with the current set of knots.          c
c   if fp > s we will increase the number of knots and compute the     c
c      corresponding least-squares spline until finally  fp<=s.        c
c the initial choice of knots depends on the value of s and iopt.      c
c   if iopt=0 we first compute the least-squares polynomial of degree  c
c     kx in x and ky in y; nx=nminx=2*kx+2 and ny=nminy=2*ky+2.        c
c     fp0=f(0) denotes the corresponding weighted sum of squared       c
c     residuals                                                        c
c   if iopt=1 we start with the knots found at the last call of the    c
c     routine, except for the case that s>=fp0; then we can compute    c
c     the least-squares polynomial directly.                           c
c eventually the independent variables x and y (and the corresponding  c
c parameters) will be switched if this can reduce the bandwidth of the c
c system to be solved.                                                 c
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c  ichang denotes whether(1) or not(-1) the directions have been inter-
c  changed.
      ichang = -1
      x0 = xb
      x1 = xe
      y0 = yb
      y1 = ye
      kx = kxx
      ky = kyy
      kx1 = kx+1
      ky1 = ky+1
      nxe = nxest
      nye = nyest
      eps = sqrt(eta)
      if(iopt.lt.0) go to 20
c  calculation of acc, the absolute tolerance for the root of f(p)=s.
      acc = tol*s
      if(iopt.eq.0) go to 10
      if(fp0.gt.s) go to 20
c  initialization for the least-squares polynomial.
  10  nminx = 2*kx1
      nminy = 2*ky1
      nx = nminx
      ny = nminy
      ier = -2
      go to 30
  20  nx = nx0
      ny = ny0
c  main loop for the different sets of knots. m is a save upper bound
c  for the number of trials.
  30  do 420 iter=1,m
c  find the position of the additional knots which are needed for the
c  b-spline representation of s(x,y).
        l = nx
        do 40 i=1,kx1
          tx(i) = x0
          tx(l) = x1
          l = l-1
  40    continue
        l = ny
        do 50 i=1,ky1
          ty(i) = y0
          ty(l) = y1
          l = l-1
  50    continue
c  find nrint, the total number of knot intervals and nreg, the number
c  of panels in which the approximation domain is subdivided by the
c  intersection of knots.
        nxx = nx-2*kx1+1
        nyy = ny-2*ky1+1
        nrint = nxx+nyy
        nreg = nxx*nyy
c  find the bandwidth of the observation matrix a.
c  if necessary, interchange the variables x and y, in order to obtain
c  a minimal bandwidth.
        iband1 = kx*(ny-ky1)+ky
        l = ky*(nx-kx1)+kx
        if(iband1.le.l) go to 130
        iband1 = l
        ichang = -ichang
        do 60 i=1,m
          store = x(i)
          x(i) = y(i)
          y(i) = store
  60    continue
        store = x0
        x0 = y0
        y0 = store
        store = x1
        x1 = y1
        y1 = store
        n = min0(nx,ny)
        do 70 i=1,n
          store = tx(i)
          tx(i) = ty(i)
          ty(i) = store
  70    continue
        n1 = n+1

ccc        if(nx-ny) 80,120,100  ! obsolete
        if( (nx-ny) .LT. 0 ) goto  80
        if( (nx-ny) .EQ. 0 ) goto 120
        if( (nx-ny) .GT. 0 ) goto 100

  80    do 90 i=n1,ny
          tx(i) = ty(i)
  90    continue
        go to 120
 100    do 110 i=n1,nx
          ty(i) = tx(i)
 110    continue
 120    l = nx
        nx = ny
        ny = l
        l = nxe
        nxe = nye
        nye = l
        l = nxx
        nxx = nyy
        nyy = l
        l = kx
        kx = ky
        ky = l
        kx1 = kx+1
        ky1 = ky+1
 130    iband = iband1+1
c  arrange the data points according to the panel they belong to.
        call fporde(x,y,m,kx,ky,tx,nx,ty,ny,nummer,index,nreg)
c  find ncof, the number of b-spline coefficients.
        nk1x = nx-kx1
        nk1y = ny-ky1
        ncof = nk1x*nk1y
c  initialize the observation matrix a.
        do 140 i=1,ncof
          f(i) = 0.
          do 141 j=1,iband
            a(i,j) = 0.
 141    continue   ! RK
 140    continue
c  initialize the sum of squared residuals.
        fp = 0.
c  fetch the data points in the new order. main loop for the
c  different panels.
        do 250 num=1,nreg
c  fix certain constants for the current panel; jrot records the column
c  number of the first non-zero element in a row of the observation
c  matrix according to a data point of the panel.
          num1 = num-1
          lx = num1/nyy
          l1 = lx+kx1
          ly = num1-lx*nyy
          l2 = ly+ky1
          jrot = lx*nk1y+ly
c  test whether there are still data points in the panel.
          in = index(num)
 150      if(in.eq.0) go to 250
c  fetch a new data point.
          wi = w(in)
          zi = z(in)*wi
c  evaluate for the x-direction, the (kx+1) non-zero b-splines at x(in).
          call fpbspl(tx,nx,kx,x(in),l1,hx)
c  evaluate for the y-direction, the (ky+1) non-zero b-splines at y(in).
          call fpbspl(ty,ny,ky,y(in),l2,hy)
c  store the value of these b-splines in spx and spy respectively.
          do 160 i=1,kx1
            spx(in,i) = hx(i)
 160      continue
          do 170 i=1,ky1
            spy(in,i) = hy(i)
 170      continue
c  initialize the new row of observation matrix.
          do 180 i=1,iband
            h(i) = 0.
 180      continue
c  calculate the non-zero elements of the new row by making the cross
c  products of the non-zero b-splines in x- and y-direction.
          i1 = 0
          do 200 i=1,kx1
            hxi = hx(i)
            j1 = i1
            do 190 j=1,ky1
              j1 = j1+1
              h(j1) = hxi*hy(j)*wi
 190        continue
            i1 = i1+nk1y
 200      continue
c  rotate the row into triangle by givens transformations .
          irot = jrot
          do 220 i=1,iband
            irot = irot+1
            piv = h(i)
            if(piv.eq.0.) go to 220
c  calculate the parameters of the givens transformation.
            call fpgivs(piv,a(irot,1),cos,sin)
c  apply that transformation to the right hand side.
            call fprota(cos,sin,zi,f(irot))
            if(i.eq.iband) go to 230
c  apply that transformation to the left hand side.
            i2 = 1
            i3 = i+1
            do 210 j=i3,iband
              i2 = i2+1
              call fprota(cos,sin,h(j),a(irot,i2))
 210        continue
 220      continue
c  add the contribution of the row to the sum of squares of residual
c  right hand sides.
 230      fp = fp+zi**2
c  find the number of the next data point in the panel.
c xxx 240      in = nummer(in)
          in = nummer(in)
          go to 150
 250    continue
c  find dmax, the maximum value for the diagonal elements in the reduced
c  triangle.
        dmax = 0.
        do 260 i=1,ncof
          if(a(i,1).le.dmax) go to 260
          dmax = a(i,1)
 260    continue
c  check whether the observation matrix is rank deficient.
        sigma = eps*dmax
        do 270 i=1,ncof
          if(a(i,1).le.sigma) go to 280
 270    continue
c  backward substitution in case of full rank.
        call fpback(a,f,ncof,iband,c,nc)
        rank = ncof
        do 275 i=1,ncof
          q(i,1) = a(i,1)/dmax
 275    continue
        go to 300
c  in case of rank deficiency, find the minimum norm solution.
c  check whether there is sufficient working space
 280    lwest = ncof*iband+ncof+iband
        if(lwrk.lt.lwest) go to 780
        do 290 i=1,ncof
          ff(i) = f(i)
          do 291 j=1,iband
            q(i,j) = a(i,j)
 291    continue   ! RK
 290    continue
        lf =1
        lh = lf+ncof
        la = lh+iband
        call fprank(q,ff,ncof,iband,nc,sigma,c,sq,rank,wrk(la),
     *    wrk(lf),wrk(lh))
        do 295 i=1,ncof
          q(i,1) = q(i,1)/dmax
 295    continue
c  add to the sum of squared residuals, the contribution of reducing
c  the rank.
        fp = fp+sq
 300    if(ier.eq.(-2)) fp0 = fp
c  test whether the least-squares spline is an acceptable solution.
        if(iopt.lt.0) go to 820
        fpms = fp-s
        if(abs(fpms).le.acc) then
ccc           if(fp) 815,815,820  ! obsolete
           if ( fp .LT. 0 ) GOTO 815
           if ( fp .EQ. 0 ) GOTO 815
           if ( fp .GT. 0 ) GOTO 820
        endif
c  test whether we can accept the choice of knots.
        if(fpms.lt.0.) go to 430
c  test whether we cannot further increase the number of knots.
        if(ncof.gt.m) go to 790
        ier = 0
c  search where to add a new knot.
c  find for each interval the sum of squared residuals fpint for the
c  data points having the coordinate belonging to that knot interval.
c  calculate also coord which is the same sum, weighted by the position
c  of the data points considered.
c xxxx 310    do 320 i=1,nrint
        do 320 i=1,nrint
          fpint(i) = 0.
          coord(i) = 0.
 320    continue
        do 360 num=1,nreg
          num1 = num-1
          lx = num1/nyy
          l1 = lx+1
          ly = num1-lx*nyy
          l2 = ly+1+nxx
          jrot = lx*nk1y+ly
          in = index(num)
 330      if(in.eq.0) go to 360
          store = 0.
          i1 = jrot
          do 350 i=1,kx1
            hxi = spx(in,i)
            j1 = i1
            do 340 j=1,ky1
              j1 = j1+1
              store = store+hxi*spy(in,j)*c(j1)
 340        continue
            i1 = i1+nk1y
 350      continue
          store = (w(in)*(z(in)-store))**2
          fpint(l1) = fpint(l1)+store
          coord(l1) = coord(l1)+store*x(in)
          fpint(l2) = fpint(l2)+store
          coord(l2) = coord(l2)+store*y(in)
          in = nummer(in)
          go to 330
 360    continue
c  find the interval for which fpint is maximal on the condition that
c  there still can be added a knot.
 370    l = 0
        fpmax = 0.
        l1 = 1
        l2 = nrint
        if(nx.eq.nxe) l1 = nxx+1
        if(ny.eq.nye) l2 = nxx
        if(l1.gt.l2) go to 810
        do 380 i=l1,l2
          if(fpmax.ge.fpint(i)) go to 380
          l = i
          fpmax = fpint(i)
 380    continue
c  test whether we cannot further increase the number of knots.
        if(l.eq.0) go to 785
c  calculate the position of the new knot.
        arg = coord(l)/fpint(l)
c  test in what direction the new knot is going to be added.
        if(l.gt.nxx) go to 400
c  addition in the x-direction.
        jxy = l+kx1
        fpint(l) = 0.
        fac1 = tx(jxy)-arg
        fac2 = arg-tx(jxy-1)
        if(fac1.gt.(ten*fac2) .or. fac2.gt.(ten*fac1)) go to 370
        j = nx
        do 390 i=jxy,nx
          tx(j+1) = tx(j)
          j = j-1
 390    continue
        tx(jxy) = arg
        nx = nx+1
        go to 420
c  addition in the y-direction.
 400    jxy = l+ky1-nxx
        fpint(l) = 0.
        fac1 = ty(jxy)-arg
        fac2 = arg-ty(jxy-1)
        if(fac1.gt.(ten*fac2) .or. fac2.gt.(ten*fac1)) go to 370
        j = ny
        do 410 i=jxy,ny
          ty(j+1) = ty(j)
          j = j-1
 410    continue
        ty(jxy) = arg
        ny = ny+1
c  restart the computations with the new set of knots.
 420  continue
c  test whether the least-squares polynomial is a solution of our
c  approximation problem.
 430  if(ier.eq.(-2)) go to 830
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c part 2: determination of the smoothing spline sp(x,y)                c
c *****************************************************                c
c we have determined the number of knots and their position. we now    c
c compute the b-spline coefficients of the smoothing spline sp(x,y).   c
c the observation matrix a is extended by the rows of a matrix,        c
c expressing that sp(x,y) must be a polynomial of degree kx in x and   c
c ky in y. the corresponding weights of these additional rows are set  c
c to 1./p.  iteratively we than have to determine the value of p       c
c such that f(p)=sum((w(i)*(z(i)-sp(x(i),y(i))))**2) be = s.           c
c we already know that the least-squares polynomial corresponds to     c
c p=0  and that the least-squares spline corresponds to p=infinity.    c
c the iteration process which is proposed here makes use of rational   c
c interpolation. since f(p) is a convex and strictly decreasing        c
c function of p, it can be approximated by a rational function r(p)=   c
c (u*p+v)/(p+w). three values of p(p1,p2,p3) with corresponding values c
c of f(p) (f1=f(p1)-s,f2=f(p2)-s,f3=f(p3)-s) are used to calculate the c
c new value of p such that r(p)=s. convergence is guaranteed by taking c
c f1 > 0 and f3 < 0.                                                   c
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
      kx2 = kx1+1
c  test whether there are interior knots in the x-direction.
      if(nk1x.eq.kx1) go to 440
c  evaluate the discotinuity jumps of the kx-th order derivative of
c  the b-splines at the knots tx(l),l=kx+2,...,nx-kx-1.
      call fpdisc(tx,nx,kx2,bx,nmax)
 440  ky2 = ky1 + 1
c  test whether there are interior knots in the y-direction.
      if(nk1y.eq.ky1) go to 450
c  evaluate the discontinuity jumps of the ky-th order derivative of
c  the b-splines at the knots ty(l),l=ky+2,...,ny-ky-1.
      call fpdisc(ty,ny,ky2,by,nmax)
c  initial value for p.
 450  p1 = 0.
      f1 = fp0-s
      p3 = -one
      f3 = fpms
      p = 0.
      do 460 i=1,ncof
        p = p+a(i,1)
 460  continue
      rn = ncof
      p = rn/p
c  find the bandwidth of the extended observation matrix.
      iband3 = kx1*nk1y
      iband4 = iband3 +1
      ich1 = 0
      ich3 = 0
c  iteration process to find the root of f(p)=s.
      do 770 iter=1,maxit
        pinv = one/p
c  store the triangularized observation matrix into q.
        do 480 i=1,ncof
          ff(i) = f(i)
          do 470 j=1,iband
            q(i,j) = a(i,j)
 470      continue
          ibb = iband+1
          do 481 j=ibb,iband4
            q(i,j) = 0.
 481    continue
 480    continue
        if(nk1y.eq.ky1) go to 560
c  extend the observation matrix with the rows of a matrix, expressing
c  that for x=cst. sp(x,y) must be a polynomial in y of degree ky.
        do 550 i=ky2,nk1y
          ii = i-ky1
          do 551 j=1,nk1x  ! RK
c  initialize the new row.
            do 490 l=1,iband
              h(l) = 0.
 490        continue
c  fill in the non-zero elements of the row. jrot records the column
c  number of the first non-zero element in the row.
            do 500 l=1,ky2
              h(l) = by(ii,l)*pinv
 500        continue
            zi = 0.
            jrot = (j-1)*nk1y+ii
c  rotate the new row into triangle by givens transformations without
c  square roots.
            do 540 irot=jrot,ncof
              piv = h(1)
              i2 = min0(iband1,ncof-irot)
              if(piv.eq.0.) then

                 if ( i2 .LT. 0 ) goto 551  ! RK 550 -> 551
                 if ( i2 .EQ. 0 ) goto 550  ! RK 550 -> 551
                 if ( i2 .GT. 0 ) goto 520
              endif
c  calculate the parameters of the givens transformation.
              call fpgivs(piv,q(irot,1),cos,sin)
c  apply that givens transformation to the right hand side.
              call fprota(cos,sin,zi,ff(irot))
              if(i2.eq.0) go to 551  ! RK 550 -> 551
c  apply that givens transformation to the left hand side.
              do 510 l=1,i2
                l1 = l+1
                call fprota(cos,sin,h(l1),q(irot,l1))
 510          continue
 520          do 530 l=1,i2
                h(l) = h(l+1)
 530          continue
              h(i2+1) = 0.
 540        continue

 551    continue
 550    continue
 560    if(nk1x.eq.kx1) go to 640
c  extend the observation matrix with the rows of a matrix expressing
c  that for y=cst. sp(x,y) must be a polynomial in x of degree kx.
        do 630 i=kx2,nk1x
          ii = i-kx1
          do 631 j=1,nk1y
c  initialize the new row
            do 570 l=1,iband4
              h(l) = 0.
 570        continue
c  fill in the non-zero elements of the row. jrot records the column
c  number of the first non-zero element in the row.
            j1 = 1
            do 580 l=1,kx2
              h(j1) = bx(ii,l)*pinv
              j1 = j1+nk1y
 580        continue
            zi = 0.
            jrot = (i-kx2)*nk1y+j
c  rotate the new row into triangle by givens transformations .
            do 620 irot=jrot,ncof
              piv = h(1)
              i2 = min0(iband3,ncof-irot)
              if(piv.eq.0.) then

                if ( i2 .LT. 0 ) goto 631 ! RK 630 -> 631
                if ( i2 .EQ. 0 ) goto 631
                if ( i2 .GT. 0 ) goto 600
              endif
c  calculate the parameters of the givens transformation.
              call fpgivs(piv,q(irot,1),cos,sin)
c  apply that givens transformation to the right hand side.
              call fprota(cos,sin,zi,ff(irot))
              if(i2.eq.0) go to 631  ! RK
c  apply that givens transformation to the left hand side.
              do 590 l=1,i2
                l1 = l+1
                call fprota(cos,sin,h(l1),q(irot,l1))
 590          continue
 600          do 610 l=1,i2
                h(l) = h(l+1)
 610          continue
              h(i2+1) = 0.
 620        continue
 631    continue  ! RK
 630    continue
c  find dmax, the maximum value for the diagonal elements in the
c  reduced triangle.
 640    dmax = 0.
        do 650 i=1,ncof
          if(q(i,1).le.dmax) go to 650
          dmax = q(i,1)
 650    continue
c  check whether the matrix is rank deficient.
        sigma = eps*dmax
        do 660 i=1,ncof
          if(q(i,1).le.sigma) go to 670
 660    continue
c  backward substitution in case of full rank.
        call fpback(q,ff,ncof,iband4,c,nc)
        rank = ncof
        go to 675
c  in case of rank deficiency, find the minimum norm solution.
 670    lwest = ncof*iband4+ncof+iband4
        if(lwrk.lt.lwest) go to 780
        lf = 1
        lh = lf+ncof
        la = lh+iband4
        call fprank(q,ff,ncof,iband4,nc,sigma,c,sq,rank,wrk(la),
     *   wrk(lf),wrk(lh))
 675    do 680 i=1,ncof
          q(i,1) = q(i,1)/dmax
 680    continue
c  compute f(p).
        fp = 0.
        do 720 num = 1,nreg
          num1 = num-1
          lx = num1/nyy
          ly = num1-lx*nyy
          jrot = lx*nk1y+ly
          in = index(num)
 690      if(in.eq.0) go to 720
          store = 0.
          i1 = jrot
          do 710 i=1,kx1
            hxi = spx(in,i)
            j1 = i1
            do 700 j=1,ky1
              j1 = j1+1
              store = store+hxi*spy(in,j)*c(j1)
 700        continue
            i1 = i1+nk1y
 710      continue
          fp = fp+(w(in)*(z(in)-store))**2
          in = nummer(in)
          go to 690
 720    continue
c  test whether the approximation sp(x,y) is an acceptable solution.
        fpms = fp-s
        if(abs(fpms).le.acc) go to 820
c  test whether the maximum allowable number of iterations has been
c  reached.
        if(iter.eq.maxit) go to 795
c  carry out one more step of the iteration process.
        p2 = p
        f2 = fpms
        if(ich3.ne.0) go to 740
        if((f2-f3).gt.acc) go to 730
c  our initial choice of p is too large.
        p3 = p2
        f3 = f2
        p = p*con4
        if(p.le.p1) p = p1*con9 + p2*con1
        go to 770
 730    if(f2.lt.0.) ich3 = 1
 740    if(ich1.ne.0) go to 760
        if((f1-f2).gt.acc) go to 750
c  our initial choice of p is too small
        p1 = p2
        f1 = f2
        p = p/con4
        if(p3.lt.0.) go to 770
        if(p.ge.p3) p = p2*con1 + p3*con9
        go to 770
 750    if(f2.gt.0.) ich1 = 1
c  test whether the iteration process proceeds as theoretically
c  expected.
 760    if(f2.ge.f1 .or. f2.le.f3) go to 800
c  find the new value of p.
        p = fprati(p1,f1,p2,f2,p3,f3)
 770  continue
c  error codes and messages.
 780  ier = lwest
      go to 830
 785  ier = 5
      go to 830
 790  ier = 4
      go to 830
 795  ier = 3
      go to 830
 800  ier = 2
      go to 830
 810  ier = 1
      go to 830
 815  ier = -1
      fp = 0.
 820  if(ncof.ne.rank) ier = -rank
c  test whether x and y are in the original order.
 830  if(ichang.lt.0) go to 930
c  if not, interchange x and y once more.
      l1 = 1
      do 840 i=1,nk1x
        l2 = i
        do 841 j=1,nk1y
          f(l2) = c(l1)
          l1 = l1+1
          l2 = l2+nk1x
 841  continue    ! RK
 840  continue
      do 850 i=1,ncof
        c(i) = f(i)
 850  continue
      do 860 i=1,m
        store = x(i)
        x(i) = y(i)
        y(i) = store
 860  continue
      n = min0(nx,ny)
      do 870 i=1,n
        store = tx(i)
        tx(i) = ty(i)
        ty(i) = store
 870  continue
      n1 = n+1
ccc      if(nx-ny) 880,920,900  ! obsolete
      if( (nx-ny) .LT. 0 ) GOTO 880
      if( (nx-ny) .EQ. 0 ) GOTO 920
      if( (nx-ny) .GT. 0 ) GOTO 900

 880  do 890 i=n1,ny
        tx(i) = ty(i)
 890  continue
      go to 920
 900  do 910 i=n1,nx
        ty(i) = tx(i)
 910  continue
 920  l = nx
      nx = ny
      ny = l
 930  if(iopt.lt.0) go to 940
      nx0 = nx
      ny0 = ny
 940  return
      end

      subroutine fpdisc(t,n,k2,b,nest)
      IMPLICIT NONE
c  subroutine fpdisc calculates the discontinuity jumps of the kth
c  derivative of the b-splines of degree k at the knots t(k+2)..t(n-k-1)
c  ..scalar arguments..
      integer n,k2,nest
c  ..array arguments..
      real*8 t(n),b(nest,k2)
c  ..local scalars..
      real*8 an,fac,prod
      integer i,ik,j,jk,k,k1,l,lj,lk,lmk,lp,nk1,nrint
c  ..local array..
      real*8 h(12)
c  ..
      k1 = k2-1
      k = k1-1
      nk1 = n-k1
      nrint = nk1-k
      an = nrint
      fac = an/(t(nk1+1)-t(k1))
      do 40 l=k2,nk1
        lmk = l-k1
        do 10 j=1,k1
          ik = j+k1
          lj = l+j
          lk = lj-k2
          h(j) = t(l)-t(lk)
          h(ik) = t(l)-t(lj)
  10    continue
        lp = lmk
        do 30 j=1,k2
          jk = j
          prod = h(j)
          do 20 i=1,k
            jk = jk+1
            prod = prod*h(jk)*fac
  20      continue
          lk = lp+k1
          b(lmk,j) = (t(lk)-t(lp))/prod
          lp = lp+1
  30    continue
  40  continue
      return
      end

      subroutine fpgivs(piv,ww,cos,sin)
      IMPLICIT NONE
c  subroutine fpgivs calculates the parameters of a givens
c  transformation .
c  ..
c  ..scalar arguments..
      real*8 piv,ww,cos,sin
c  ..local scalars..
      real*8 dd,one,store
c  ..function references..
      real*8 abs,sqrt
c  ..
      one = 0.1e+01
      store = abs(piv)
      if(store.ge.ww) dd = store*sqrt(one+(ww/piv)**2)
      if(store.lt.ww) dd = ww*sqrt(one+(piv/ww)**2)
      cos = ww/dd
      sin = piv/dd
      ww = dd
      return
      end

      subroutine fprank(a,f,n,m,na,tol,c,sq,rank,aa,ff,h)
      IMPLICIT NONE
c  subroutine fprank finds the minimum norm solution of a least-
c  squares problem in case of rank deficiency.
c
c  input parameters:
c    a : array, which contains the non-zero elements of the observation
c        matrix after triangularization by givens transformations.
c    f : array, which contains the transformed right hand side.
c    n : integer,wich contains the dimension of a.
c    m : integer, which denotes the bandwidth of a.
c  tol : real value, giving a threshold to determine the rank of a.
c
c  output parameters:
c    c : array, which contains the minimum norm solution.
c   sq : real value, giving the contribution of reducing the rank
c        to the sum of squared residuals.
c rank : integer, which contains the rank of matrix a.
c
c  ..scalar arguments..
      integer n,m,na,rank
      real*8 tol,sq
c  ..array arguments..
      real*8 a(na,m),f(n),c(n),aa(n,m),ff(n),h(m)
c  ..local scalars..
      integer i,ii,ij,i1,i2,j,jj,j1,j2,j3,k,kk,m1,nl
      real*8 cos,fac,piv,sin,yi
      double precision store,stor1,stor2,stor3
c  ..function references..
      integer min0
c  ..subroutine references..
c    fpgivs,fprota
c  ..
      m1 = m-1
c  the rank deficiency nl is considered to be the number of sufficient
c  small diagonal elements of a.
      nl = 0
      sq = 0.
      do 90 i=1,n
        if(a(i,1).gt.tol) go to 90
c  if a sufficient small diagonal element is found, we put it to
c  zero. the remainder of the row corresponding to that zero diagonal
c  element is then rotated into triangle by givens rotations .
c  the rank deficiency is increased by one.
        nl = nl+1
        if(i.eq.n) go to 90
        yi = f(i)
        do 10 j=1,m1
          h(j) = a(i,j+1)
  10    continue
        h(m) = 0.
        i1 = i+1
        do 60 ii=i1,n
          i2 = min0(n-ii,m1)
          piv = h(1)
          if(piv.eq.0.) go to 30
          call fpgivs(piv,a(ii,1),cos,sin)
          call fprota(cos,sin,yi,f(ii))
          if(i2.eq.0) go to 70
          do 20 j=1,i2
            j1 = j+1
            call fprota(cos,sin,h(j1),a(ii,j1))
            h(j) = h(j1)
  20      continue
          go to 50
  30      if(i2.eq.0) go to 70
          do 40 j=1,i2
            h(j) = h(j+1)
  40      continue
  50      h(i2+1) = 0.
  60    continue
c  add to the sum of squared residuals the contribution of deleting
c  the row with small diagonal element.
  70    sq = sq+yi**2
  90  continue
c  rank denotes the rank of a.
      rank = n-nl
c  let b denote the (rank*n) upper trapezoidal matrix which can be
c  obtained from the (n*n) upper triangular matrix a by deleting
c  the rows and interchanging the columns corresponding to a zero
c  diagonal element. if this matrix is factorized using givens
c  transformations as  b = (r) (u)  where
c    r is a (rank*rank) upper triangular matrix,
c    u is a (rank*n) orthonormal matrix
c  then the minimal least-squares solution c is given by c = b' v,
c  where v is the solution of the system  (r) (r)' v = g  and
c  g denotes the vector obtained from the old right hand side f, by
c  removing the elements corresponding to a zero diagonal element of a.
c  initialization.
      do 100 i=1,rank
        do 101 j=1,m
          aa(i,j) = 0.
 101  continue  ! RK
 100  continue
c  form in aa the upper triangular matrix obtained from a by
c  removing rows and columns with zero diagonal elements. form in ff
c  the new right hand side by removing the elements of the old right
c  hand side corresponding to a deleted row.
      ii = 0
      do 120 i=1,n
        if(a(i,1).le.tol) go to 120
        ii = ii+1
        ff(ii) = f(i)
        aa(ii,1) = a(i,1)
        jj = ii
        kk = 1
        j = i
        j1 = min0(j-1,m1)
        if(j1.eq.0) go to 120
        do 110 k=1,j1
          j = j-1
          if(a(j,1).le.tol) go to 110
          kk = kk+1
          jj = jj-1
          aa(jj,kk) = a(j,k+1)
 110    continue
 120  continue
c  form successively in h the columns of a with a zero diagonal element.
      ii = 0
      do 200 i=1,n
        ii = ii+1
        if(a(i,1).gt.tol) go to 200
        ii = ii-1
        if(ii.eq.0) go to 200
        jj = 1
        j = i
        j1 = min0(j-1,m1)
        do 130 k=1,j1
          j = j-1
          if(a(j,1).le.tol) go to 130
          h(jj) = a(j,k+1)
          jj = jj+1
 130    continue
        do 140 kk=jj,m
          h(kk) = 0.
 140    continue
c  rotate this column into aa by givens transformations.
        jj = ii
        do 190 i1=1,ii
          j1 = min0(jj-1,m1)
          piv = h(1)
          if(piv.ne.0.) go to 160
          if(j1.eq.0) go to 200
          do 150 j2=1,j1
            j3 = j2+1
            h(j2) = h(j3)
 150      continue
          go to 180
 160      call fpgivs(piv,aa(jj,1),cos,sin)
          if(j1.eq.0) go to 200
          kk = jj
          do 170 j2=1,j1
            j3 = j2+1
            kk = kk-1
            call fprota(cos,sin,h(j3),aa(kk,j3))
            h(j2) = h(j3)
 170      continue
 180      jj = jj-1
          h(j3) = 0.
 190    continue
 200  continue
c  solve the system (aa) (f1) = ff
      ff(rank) = ff(rank)/aa(rank,1)
      i = rank-1
      if(i.eq.0) go to 230
      do 220 j=2,rank
        store = ff(i)
        i1 = min0(j-1,m1)
        k = i
        do 210 ii=1,i1
          k = k+1
          stor1 = ff(k)
          stor2 = aa(i,ii+1)
          store = store-stor1*stor2
 210    continue
        stor1 = aa(i,1)
        ff(i) = store/stor1
        i = i-1
 220  continue
c  solve the system  (aa)' (f2) = f1
 230  ff(1) = ff(1)/aa(1,1)
      if(rank.eq.1) go to 260
      do 250 j=2,rank
        store = ff(j)
        i1 = min0(j-1,m1)
        k = j
        do 240 ii=1,i1
          k = k-1
          stor1 = ff(k)
          stor2 = aa(k,ii+1)
          store = store-stor1*stor2
 240    continue
        stor1 = aa(j,1)
        ff(j) = store/stor1
 250  continue
c  premultiply f2 by the transpoze of a.
 260  k = 0
      do 280 i=1,n
        store = 0.
        if(a(i,1).gt.tol) k = k+1
        j1 = min0(i,m)
        kk = k
        ij = i+1
        do 270 j=1,j1
          ij = ij-1
          if(a(ij,1).le.tol) go to 270
          stor1 = a(ij,j)
          stor2 = ff(kk)
          store = store+stor1*stor2
          kk = kk-1
 270    continue
        c(i) = store
 280  continue
c  add to the sum of squared residuals the contribution of putting
c  to zero the small diagonal elements of matrix (a).
      stor3 = 0.
      do 310 i=1,n
        if(a(i,1).gt.tol) go to 310
        store = f(i)
        i1 = min0(n-i,m1)
        if(i1.eq.0) go to 300
        do 290 j=1,i1
          ij = i+j
          stor1 = c(ij)
          stor2 = a(i,j+1)
          store = store-stor1*stor2
 290    continue
 300    fac = a(i,1)*c(i)
        stor1 = a(i,1)
        stor2 = c(i)
        stor1 = stor1*stor2
        stor3 = stor3+stor1*(stor1-store-store)
 310  continue
      fac = stor3
      sq = sq+fac
      return
      end

      real*8 function fprati(p1,f1,p2,f2,p3,f3)
c  given three points (p1,f1),(p2,f2) and (p3,f3), function fprati
c  gives the value of p such that the rational interpolating function
c  of the form r(p) = (u*p+v)/(p+w) equals zero at p.
c  ..
c  ..scalar arguments..
      real*8 p1,f1,p2,f2,p3,f3
c  ..local scalars..
      real*8 h1,h2,h3,p
c  ..
      if(p3.gt.0.) go to 10
c  value of p in case p3 = infinity.
      p = (p1*(f1-f3)*f2-p2*(f2-f3)*f1)/((f1-f2)*f3)
      go to 20
c  value of p in case p3 ^= infinity.
  10  h1 = f1*(f2-f3)
      h2 = f2*(f3-f1)
      h3 = f3*(f1-f2)
      p = -(p1*p2*h3+p2*p3*h1+p3*p1*h2)/(p1*h1+p2*h2+p3*h3)
c  adjust the value of p1,f1,p3 and f3 such that f1 > 0 and f3 < 0.
  20  if(f2.lt.0.) go to 30
      p1 = p2
      f1 = f2
      go to 40
  30  p3 = p2
      f3 = f2
  40  fprati = p
      return
      end

      subroutine fprota(cos,sin,a,b)
      IMPLICIT NONE
c  subroutine fprota applies a givens rotation to a and b.
c  ..
c  ..scalar arguments..
      real*8 cos,sin,a,b
c ..local scalars..
      real*8 stor1,stor2
c  ..
      stor1 = a
      stor2 = b
      b = cos*stor2+sin*stor1
      a = cos*stor1-sin*stor2
      return
      end

      subroutine fporde(x,y,m,kx,ky,tx,nx,ty,ny,nummer,index,nreg)
      IMPLICIT NONE
c  subroutine fporde sorts the data points (x(i),y(i)),i=1,2,...,m
c  according to the panel tx(l)<=x<tx(l+1),ty(k)<=y<ty(k+1), they belong
c  to. for each panel a stack is constructed  containing the numbers
c  of data points lying inside; index(j),j=1,2,...,nreg points to the
c  first data point in the jth panel while nummer(i),i=1,2,...,m gives
c  the number of the next data point in the panel.
c  ..
c  ..scalar arguments..
      integer m,kx,ky,nx,ny,nreg
c  ..array arguments..
      real*8 x(m),y(m),tx(nx),ty(ny)
      integer nummer(m),index(nreg)
c  ..local scalars..
      real*8 xi,yi
      integer i,im,k,kx1,ky1,k1,l,l1,nk1x,nk1y,num,nyy
c  ..
      kx1 = kx+1
      ky1 = ky+1
      nk1x = nx-kx1
      nk1y = ny-ky1
      nyy = nk1y-ky
      do 10 i=1,nreg
        index(i) = 0
  10  continue
      do 60 im=1,m
        xi = x(im)
        yi = y(im)
        l = kx1
        l1 = l+1
  20    if(xi.lt.tx(l1) .or. l.eq.nk1x) go to 30
        l = l1
        l1 = l+1
        go to 20
  30    k = ky1
        k1 = k+1
  40    if(yi.lt.ty(k1) .or. k.eq.nk1y) go to 50
        k = k1
        k1 = k+1
        go to 40
  50    num = (l-kx1)*nyy+k-ky
        nummer(im) = index(num)
        index(num) = im
  60  continue
      return
      end

      subroutine bispev(tx,nx,ty,ny,c,kx,ky,x,mx,y,my,z,wrk,lwrk,
     * iwrk,kwrk,ier)
      IMPLICIT NONE
c  subroutine bispev evaluates on a grid (x(i),y(j)),i=1,...,mx; j=1,...
c  ,my a bivariate spline s(x,y) of degrees kx and ky, given in the
c  b-spline representation.
c
c  calling sequence:
c     call bispev(tx,nx,ty,ny,c,kx,ky,x,mx,y,my,z,wrk,lwrk,
c    * iwrk,kwrk,ier)
c
c  input parameters:
c   tx    : real array, length nx, which contains the position of the
c           knots in the x-direction.
c   nx    : integer, giving the total number of knots in the x-direction
c   ty    : real array, length ny, which contains the position of the
c           knots in the y-direction.
c   ny    : integer, giving the total number of knots in the y-direction
c   c     : real array, length (nx-kx-1)*(ny-ky-1), which contains the
c           b-spline coefficients.
c   kx,ky : integer values, giving the degrees of the spline.
c   x     : real array of dimension (mx).
c           before entry x(i) must be set to the x co-ordinate of the
c           i-th grid point along the x-axis.
c           tx(kx+1)<=x(i-1)<=x(i)<=tx(nx-kx), i=2,...,mx.
c   mx    : on entry mx must specify the number of grid points along
c           the x-axis. mx >=1.
c   y     : real array of dimension (my).
c           before entry y(j) must be set to the y co-ordinate of the
c           j-th grid point along the y-axis.
c           ty(ky+1)<=y(j-1)<=y(j)<=ty(ny-ky), j=2,...,my.
c   my    : on entry my must specify the number of grid points along
c           the y-axis. my >=1.
c   wrk   : real array of dimension lwrk. used as workspace.
c   lwrk  : integer, specifying the dimension of wrk.
c           lwrk >= mx*(kx+1)+my*(ky+1)
c   iwrk  : integer array of dimension kwrk. used as workspace.
c   kwrk  : integer, specifying the dimension of iwrk. kwrk >= mx+my.
c
c  output parameters:
c   z     : real array of dimension (mx*my).
c           on succesful exit z(my*(i-1)+j) contains the value of s(x,y)
c           at the point (x(i),y(j)),i=1,...,mx;j=1,...,my.
c   ier   : integer error flag
c    ier=0 : normal return
c    ier=10: invalid input data (see restrictions)
c
c  restrictions:
c   mx >=1, my >=1, lwrk>=mx*(kx+1)+my*(ky+1), kwrk>=mx+my
c   tx(kx+1) <= x(i-1) <= x(i) <= tx(nx-kx), i=2,...,mx
c   ty(ky+1) <= y(j-1) <= y(j) <= ty(ny-ky), j=2,...,my
c
c  other subroutines required:
c    fpbisp,fpbspl
c
c  references :
c    de boor c : on calculating with b-splines, j. approximation theory
c                6 (1972) 50-62.
c    cox m.g.  : the numerical evaluation of b-splines, j. inst. maths
c                applics 10 (1972) 134-149.
c    dierckx p. : curve and surface fitting with splines, monographs on
c                 numerical analysis, oxford university press, 1993.
c
c  author :
c    p.dierckx
c    dept. computer science, k.u.leuven
c    celestijnenlaan 200a, b-3001 heverlee, belgium.
c    e-mail : Paul.Dierckx@cs.kuleuven.ac.be
c
c  latest update : march 1987
c
c  ..scalar arguments..
      integer nx,ny,kx,ky,mx,my,lwrk,kwrk,ier
c  ..array arguments..
      integer iwrk(kwrk)
      real*8 tx(nx),ty(ny),c((nx-kx-1)*(ny-ky-1)),x(mx),y(my),z(mx*my),
     * wrk(lwrk)
c  ..local scalars..
      integer i,iw,lwest
c  ..
c  before starting computations a data check is made. if the input data
c  are invalid control is immediately repassed to the calling program.
      ier = 10
      lwest = (kx+1)*mx+(ky+1)*my
      if(lwrk.lt.lwest) go to 100
      if(kwrk.lt.(mx+my)) go to 100
ccc      if(mx-1) 100,30,10  ! obsolete
      if ( (mx-1) .LT. 0 ) GOTO  100
      if ( (mx-1) .EQ. 0 ) GOTO  30
      if ( (mx-1) .GT. 0 ) GOTO  10

  10  do 20 i=2,mx
        if(x(i).lt.x(i-1)) go to 100
  20  continue

  30  continue
ccc if(my-1) 100,60,40  ! obsolete
      if ( (my-1) .LT. 0 ) goto 100
      if ( (my-1) .EQ. 0 ) goto 60
      if ( (my-1) .GT. 0 ) goto 40


  40  do 50 i=2,my
        if(y(i).lt.y(i-1)) go to 100
  50  continue
  60  ier = 0
      iw = mx*(kx+1)+1
      call fpbisp(tx,nx,ty,ny,c,kx,ky,x,mx,y,my,z,wrk(1),wrk(iw),
     * iwrk(1),iwrk(mx+1))
 100  return
      end

      subroutine fpbisp(tx,nx,ty,ny,c,kx,ky,x,mx,y,my,z,wx,wy,lx,ly)
      IMPLICIT NONE
c  ..scalar arguments..
      integer nx,ny,kx,ky,mx,my
c  ..array arguments..
      integer lx(mx),ly(my)
      real*8 tx(nx),ty(ny),c((nx-kx-1)*(ny-ky-1)),x(mx),y(my),z(mx*my),
     * wx(mx,kx+1),wy(my,ky+1)
c  ..local scalars..
      integer kx1,ky1,l,l1,l2,m,nkx1,nky1,i,j,i1,j1
      real*8 arg,sp,tb,te
c  ..local arrays..
      real*8 h(6)
c  ..subroutine references..
c    fpbspl
c  ..
      kx1 = kx+1
      nkx1 = nx-kx1
      tb = tx(kx1)
      te = tx(nkx1+1)
      l = kx1
      l1 = l+1
      do 40 i=1,mx
        arg = x(i)
        if(arg.lt.tb) arg = tb
        if(arg.gt.te) arg = te
  10    if(arg.lt.tx(l1) .or. l.eq.nkx1) go to 20
        l = l1
        l1 = l+1
        go to 10
  20    call fpbspl(tx,nx,kx,arg,l,h)
        lx(i) = l-kx1
        do 30 j=1,kx1
          wx(i,j) = h(j)
  30    continue
  40  continue
      ky1 = ky+1
      nky1 = ny-ky1
      tb = ty(ky1)
      te = ty(nky1+1)
      l = ky1
      l1 = l+1
      do 80 i=1,my
        arg = y(i)
        if(arg.lt.tb) arg = tb
        if(arg.gt.te) arg = te
  50    if(arg.lt.ty(l1) .or. l.eq.nky1) go to 60
        l = l1
        l1 = l+1
        go to 50
  60    call fpbspl(ty,ny,ky,arg,l,h)
        ly(i) = l-ky1
        do 70 j=1,ky1
          wy(i,j) = h(j)
  70    continue
  80  continue
      m = 0
      do 130 i=1,mx
        l = lx(i)*nky1
        do 90 i1=1,kx1
          h(i1) = wx(i,i1)
  90    continue
        do 120 j=1,my
          l1 = l+ly(j)
          sp = 0.
          do 110 i1=1,kx1
            l2 = l1
            do 100 j1=1,ky1
              l2 = l2+1
              sp = sp+c(l2)*h(i1)*wy(j,j1)
 100        continue
            l1 = l1+nky1
 110      continue
          m = m+1
          z(m) = sp
 120    continue
 130  continue
      return
      end


C ==============================
CDECK  ID>,  SET_PEAKMJD. 
      SUBROUTINE SET_PEAKMJD()

c Created Oct 24, 2009 by R.Kessler
c
c Analyze and/or fit light curve to estimate peak-MJD.
c Fill SNLC_SEARCH_PEAKMJD to be used as the initial
c Tpeak-estimate in the light curve fit.
c
c This routine will not work properly for low SNR light curves.
c The minimum SNR on a light curve must be at least 4.
c
c Namelist variable OPT_SETPKMJD determines options;
c see OPTBIT_SETPKMJD_XXX options in global declaration.
c
c           HISTORY
c
c May 10 2016: remove PSF>2 epochs to get fluxMax (avoid crazy fluxes)
c              See new parameter PSFMAX_forFLUXMAX
c
c May 17, 2019: implement new options OPTBIT_SETPKMJD_[TRIGGER,MAXFLUX2]
c May 20, 2019: return if less then 2 epochs.
c Jan 27, 2020: use STDOUT_UPDATE flag to print screen update.
c May 01, 2020: implement SHIFT_SETPKMJD
c May 05, 2020: implement OPT_SETPKMJD_SIM option
c -------------------------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


      INTEGER
     &   EPMAX, EP
     &  ,EP_atFLUXMAX(0:MXFILT_ALL), EPTEST_atFLUXMAX(0:MXFILT_ALL)
     &  ,IFILT_OBS, ifilt, ifilt_snrmin
     &  ,IFILT_OBS2, IFILT_OUTLIER, IFILT_REJECT
     &  ,NPKMJD, LUN, VBOSE

      REAL
     &   PKMJDSUM, PKMJDAVG, PKMJDDIF, PKMJDDIF_MAX
     &  ,PKMJD, DIF, WGTSUM, WGT
     &  ,FLUX, FLUXERR, SNR, SNRMIN
     &  ,FLUXMAX(0:MXFILT_ALL)
     &  ,MJDatFLUXMAX(0:MXFILT_ALL)
     &  ,SNRatFLUXMAX(0:MXFILT_ALL)

      REAL*8
     &   MJD8, F8, PKMJD8, PKMJD8ERR, PKFLUX8, PKFLUX8ERR
     &  ,PARLIST(3), FITWIN_MJD8(2)

      LOGICAL
     &    LSET, LDMP, LDMP_USER, NOABORT, LABORT
     &   ,USEFILT(MXFILT_ALL)
     &   ,USE_MJDatFLUXMAX, USE_MJDatFMAXCLUMP
     &   ,USE_MJDatTRIGGER
     &   ,USE_SIMPKMJD
     &   ,FIRST_INIT, DOFIT, NOFIT

      CHARACTER cfilt*8, FNAM*12, METHOD*24, CCID*(MXCHAR_CCID)

c define hard-wired cut-parameters
      REAL
     &   MJDMIN_LC
     &  ,PKMJD_OUTLIER
     &  ,MAX_SNRMIN_REJECT

      PARAMETER (
     &   MJDMIN_LC           = 40000. ! min MJD to consider for light curve
     &  ,PKMJD_OUTLIER       = 30.0   ! reject PKMJD off by this much
     &  ,MAX_SNRMIN_REJECT   = 2.0    ! max SNRMIN to reject filter
     &     )

c function
      EXTERNAL init_obs_atFLUXMAX, get_obs_atFLUXMAX

C ---------------- BEGIN ----------------

      if ( OPT_SETPKMJD <= 0 ) RETURN

      FNAM = 'SET_PEAKMJD'
      CCID = SNLC_CCID

      if ( ISNLC_NEWMJD_STORE < 2 ) RETURN

c July 12 2013: check option to use MJD at max flux (no fitting)
      USE_MJDatFLUXMAX  = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_FLUXMAX)
      USE_MJDatFMAXCLUMP =
     &           BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_FLUXMAX2)
     &     .or.  BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_FLUXMAX3)
      USE_MJDatTRIGGER  = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_TRIGGER)
      USE_SIMPKMJD      = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_SIM)
      DOFIT = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_ANYFUN) .or. ! Bazin09
     &        BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_POLYCOR)
      NOFIT = (.NOT. DOFIT)

      if ( USE_MJDatTRIGGER .and. PHOTFLAG_TRIGGER == 0 ) then
        c1err = 'Must set PHOTFLAG_TRIGGER in &SNLCINP'
        c2err = 'to set PEAKMJD = MJD_TRIGGER'
        CALL MADABORT(FNAM, c1err, c2err)
      endif

c May 5 2020: check option to use true SIM_PEAKMJD
      IF ( USE_SIMPKMJD ) THEN
        if ( LSIM_SNANA ) then
            PKMJD = SIM_PEAKMJD
            GOTO 800
        else
           c1err = 'Cannot use OPT_SETPKMJD += 2048 for real data'
           c2err = 'This option (use SIM_PEAKMJD) is for sim only'
           CALL MADABORT(FNAM, c1err, c2err)
        endif
      ENDIF

c bail if the user CUTWIN_PEAKMJD does not contain  any observations:
      IF ( SNLC8_MJDMIN .GT. CUTWIN_PEAKMJD(2) ) RETURN
      IF ( SNLC8_MJDMAX .LT. CUTWIN_PEAKMJD(1) ) RETURN

c first-time init:
c  + print comments to stdout
c  + open separate log file to dump MNFIT stuff for each SN
      FIRST_INIT = (NFIT_PKMJD==0)

      IF  ( FIRST_INIT ) THEN  ! init
         LSET = .FALSE.
         print*,' '
         if ( USE_MJDatFLUXMAX ) then
            write(6,80) 'MJD at max flux' ; LSET=.TRUE.
            METHOD = '(FLuxMax)'
         else if ( USE_MJDatFMAXCLUMP ) then
            write(6,80)
     &         'MJD at max flux in dense clump of SNR-detections.'
            LSET=.TRUE.
            METHOD = '(FmaxClump)'
         else if ( USE_MJDatTRIGGER ) then
            write(6,80) 'MJD_TRIGGER' ; LSET=.TRUE.
            METHOD = '(MJD_trigger)'
         endif

         if( DOFIT ) then
            write(6,80) 'Bazin fit' ; LSET=.TRUE.
            METHOD = '(FluxMax+BazinFit)'
            if ( USE_MJDatFMAXCLUMP ) METHOD = '(FmaxClump+BazinFit)'
         endif
 80      format(' SET_PEAKMJD method: ', A)
         print*,' '
         call flush(6)

         if ( .not. LSET ) then
            write(6,80) 'UNKNOWN'
            write(c1err,86) OPT_SETPKMJD
 86         format('Unknown OPT_SETPKMJD=',I5,' in &SNLCINP.')
            c2err = 'See manual for OPT_SETPKMJD'
            CALL MADABORT(FNAM, c1err,c2err )
         endif

         VBOSE = 1
         PARLIST(1) = MJDWIN_SETPKMJD    ! user MJDWIN from &SNLCINP
         PARLIST(2) = SNRCUT_SETPKMJD    ! user SNRCUT from &SNLCINP
         PARLIST(3) = SNRMIN_forFLUXMAX  ! backup SNRCUT if above always fails
         call init_obs_atFLUXMAX(OPT_SETPKMJD, PARLIST, VBOSE)

c open outfile to dump MINUIT stdout
         if ( DOFIT ) then
            LUN = LUNPKMJD
            OPEN(UNIT=LUN,FILE=MNFIT_PKMJD_LOGFILE,status='UNKNOWN')
         endif

c open INTERP-OUT file if set

      ENDIF  ! end of FIRST_INIT

      NFIT_PKMJD = NFIT_PKMJD  + 1

      global_banner =
     &   'SET_PEAKMJD: Find Estimate of PEAK-MJD for CID='  //
     &   CCID
cc      CALL PRBANNER ( global_banner )

      IF ( NFILTDEF_SURVEY .GT. MXFILT_OBS ) THEN
        write(c1err,1661) NFILTDEF_SURVEY
        write(c2err,1662) MXFILT_OBS
1661    format('There are ', I3,' obs-filters,')
1662    format('but SET_PEAKMJD works for up to ',I2,' filters.')
        CALL MADABORT(FNAM, c1err, c2err)
      ENDIF

c initialize

      DO 480 IFILT_OBS = 0, MXFILT_ALL
         EP_atFLUXMAX(IFILT_OBS)  = -9
         FLUXMAX(IFILT_OBS)       =  0.0
         MJDatFLUXMAX(IFILT_OBS)  = -9.0
         SNRatFLUXMAX(IFILT_OBS)  = -9.0

         IF ( IFILT_OBS .EQ. 0 ) goto 480

         PKMJD_FIT(IFILT_OBS)     =  0.0
         PKMJD_ERR(IFILT_OBS)     = -9.0
         PKFLUX_FIT(IFILT_OBS)    = -9.0
         PKFLUX_ERR(IFILT_OBS)    = -9.0

         USEFILT(ifilt_obs) = .FALSE.
 480  CONTINUE


      PKMJD_ERRMIN = 1.0E9
      PKMJD_ERRWGT = 0.0

      PKFLUX_ERRMIN = 1.0E9
      PKFLUX_ERRWGT = 0.0

c find epoch with max flux for each filter using C-function

       CALL get_obs_atFLUXMAX(
     &      CCID(1:ISNLC_LENCCID)//char(0),
     &      ISNLC_NEWMJD_STORE,
     &      SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT,
     &      SNLC8_MJD, ISNLC_IFILT_OBS,
     &      EP_atFLUXMAX(0),            ! <== returned array vs. IFILTOBS
     &      MXCHAR_CCID )

c use EP at max flux to set FLUXMAX, MJD at max, SNR at max.
      DO 40 ifilt = 0, NFILTDEF_SURVEY
         if ( ifilt == 0 ) then
            ifilt_obs = 0
         else
            ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         endif
         EP = EP_atFLUXMAX(ifilt_obs)+1 ! from C code

         if ( EP < 0 ) then
           SNRatFLUXMAX(ifilt_obs) = 0.01
           MJDatFLUXMAX(ifilt_obs) = 0.01
           goto 40
         endif

         FLUX      = SNLC_FLUXCAL(EP)
         FLUXERR   = SNLC_FLUXCAL_ERRTOT(EP)

         FLUXMAX(ifilt_obs)      = FLUX
         MJDatFLUXMAX(ifilt_obs) = SNGL(SNLC8_MJD(ep))
         if ( FLUXERR > 0.0 ) then
            SNRatFLUXMAX(ifilt_obs) = FLUX/FLUXERR
         else
            SNRatFLUXMAX(ifilt_obs) = 0.0
         endif
40     CONTINUE

c -------------------------------------
c check option to use MJD at max-flux or at TRIGGER
      IF ( NOFIT ) THEN
         IF ( USE_MJDatFLUXMAX .or. USE_MJDatFMAXCLUMP ) THEN
            PKMJD  = MJDatFLUXMAX(0)
         ELSE IF ( USE_MJDatTRIGGER ) THEN
            PKMJD  = SNGL(SNLC8_MJD_TRIGGER)
         ELSE
            C1err = 'Invalid NOFIT option.'
            c2err = 'Expecting MJD-at-maxFlux or MJD-at-Trigger'
            CALL MADABORT(FNAM, c1err, c2err)
         ENDIF

         SNLC_SEARCH_PEAKMJD    = PKMJD
         IF ( STDOUT_UPDATE ) then
            write(6,50) CCID(1:ISNLC_LENCCID), PKMJD, METHOD
         ENDIF

         RETURN
      ENDIF


c --------- Below do some kind of Bazin fit -----------

c --------------
c Find valid filter with smallest SNR at epoch with max-FLux,
c and that has SNR below MAX_SNRMIN_REJECT.
c If all filters have SNR > MAX_SNRMIN_REJECT then use all filters;
c otherwise toss the one with smallest SNR at FLUXMAX.

      SNRMIN = 999999999.
      IFILT_SNRMIN = -9
      DO ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         SNR = SNRatFLUXMAX(ifilt_obs)

         if (    SNR .LT. SNRMIN
     &     .and. SNR .LT. MAX_SNRMIN_REJECT
     &     .and. SNR .GT. 0.0  ) then

            SNRMIN = SNR
            ifilt_snrmin = ifilt_obs  ! filter to reject
         endif
      ENDDO

c -----------------------------------------
c Now fit each filter to general function using MINUIT.
c Take weighted PKMJD-average so that badly measured
c PKMJD don't have much effect

      NPKMJD   = 0
      PKMJDSUM = 0.0
      WGTSUM   = 0.0
      PKMJDDIF_MAX = 0.0
      FITWIN_MJD8(1) = MJDatFLUXMAX(0) + CUTWIN_TOBS(1)
      FITWIN_MJD8(2) = MJDatFLUXMAX(0) + CUTWIN_TOBS(2)

      DO 200 ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         MJD8      = DBLE( MJDatFLUXMAX(ifilt_obs) )
         F8        = DBLE ( FLUXMAX(IFILT_OBS) )

         if ( MJD8      .LT. MJDMIN_LC    ) GOTO 200
         if ( ifilt_obs .EQ. ifilt_snrmin ) GOTO 200

         USEFILT(ifilt_obs) = .TRUE.

         CALL MNFIT_PKMJD(IFILT_OBS, FITWIN_MJD8, F8, MJD8,   ! inputs
     &              PKMJD8, PKMJD8ERR, PKFLUX8, PKFLUX8ERR)   ! return args

c store result for each filter.

           PKFLUX_FIT(ifilt_obs) = SNGL(PKFLUX8)
           PKFLUX_ERR(ifilt_obs) = SNGL(PKFLUX8ERR)

           PKMJD_FIT(ifilt_obs) = SNGL(PKMJD8)
           PKMJD_ERR(ifilt_obs) = SNGL(PKMJD8ERR)
           NPKMJD = NPKMJD + 1

c check option to interpolate flux

200   CONTINUE

      IF ( NPKMJD .EQ. 0 ) then

         NOABORT = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_NOABORT)
     &        .or. (OPT_REFORMAT_FITS > 0)
     &        .or. (.not. ABORT_ON_NOPKMJD)  ! 7.29.2014

         LABORT  = (.NOT. NOABORT)

         IF ( LABORT ) then
            C1err = 'NMJD=0 => no estimate of PKMJD !!!'
            c2err = 'Check SN ' // CCID
            CALL MADABORT(FNAM, c1err, c2err)
         ELSE
            write(6,240) CCID
 240        format(T8,'Could not estimate PKMJD for CID=',A)
            call flush(6)
            PKMJD = -1.
            GOTO 800
         ENDIF
      ENDIF

c convert sum of 1/err^2 into wgted error.
      IF  ( PKMJD_ERRWGT .GT. 0.0 ) THEN
         PKMJD_ERRWGT  = SQRT(1.0/PKMJD_ERRWGT)
      ENDIF
      IF ( PKFLUX_ERRWGT .GT. 0.0 ) THEN
         PKFLUX_ERRWGT = SQRT(1.0/PKFLUX_ERRWGT)
      ENDIF

c if there are more than 2 filters, check for
c crazy outlier.

      IFILT_REJECT    = -9
      IFILT_OUTLIER   = -9

      IF ( NPKMJD .GE. 3 ) THEN
      DO 252 ifilt_obs2 = 1, MXFILT_ALL  ! ignore this filter in average
         if ( .not. USEFILT(ifilt_obs2) ) goto 252
         PKMJDSUM = 0.0
         WGTSUM = 0.0

      DO 250 ifilt_obs  = 1, MXFILT_ALL
         if ( .not. USEFILT(ifilt_obs) ) goto 250
         if ( ifilt_obs2 .NE. ifilt_obs ) then
           PKMJDSUM = PKMJDSUM + (PKMJD_FIT(ifilt_obs)-SNGL(MJDOFF))
           WGTSUM   = WGTSUM + 1.0
         endif
250   CONTINUE

c test average against filter that was excluded

         PKMJDAVG = (PKMJDSUM/WGTSUM + SNGL(MJDOFF) )
         PKMJDDIF = abs(PKMJDAVG - PKMJD_FIT(ifilt_obs2))

         if ( PKMJDDIF .GT. PKMJDDIF_MAX ) then
            PKMJDDIF_MAX  = PKMJDDIF
            IFILT_OUTLIER = ifilt_obs2
         endif

252   CONTINUE

         if ( PKMJDDIF_MAX .GT. PKMJD_OUTLIER ) then
           USEFILT(ifilt_outlier) = .FALSE.
           IFILT_REJECT = IFILT_OUTLIER

c            print*,' xxx REJECT FILT=',IFILT_OUTLIER,
c     &       '  for CID=',CCID,'  PKMJDDIF=', PKMJDDIF_MAX
         endif

      ENDIF

c ---------------------------------------
c Finally, take PKMJD-wgted average of remaining filters.

      PKMJDSUM = 0.0
      WGTSUM   = 0.0
      NPKMJD   = 0

      DO 300 ifilt_obs = 1, MXFILT_ALL
         if ( .not. USEFILT(ifilt_obs) ) goto 300

           PKMJD8    = PKMJD_FIT(ifilt_obs)
           PKMJD8ERR = PKMJD_ERR(ifilt_obs)

           WGT    = SNGL(1.0/PKMJD8ERR) ! * 10.0/MAX(PKMJDDIF,10.0)

           PKMJDDIF = SNGL(PKMJD8 - MJDOFF)

           PKMJDSUM = PKMJDSUM + WGT*PKMJDDIF
           WGTSUM = WGTSUM + WGT
           NPKMJD = NPKMJD + 1

300   CONTINUE

      PKMJDAVG = PKMJDSUM/WGTSUM + SNGL(MJDOFF)
      PKMJD    = PKMJDAVG

      if ( STDOUT_UPDATE ) THEN
        write(6,50) CCID(1:ISNLC_LENCCID), PKMJD, METHOD
50      format(T8,'SET_PEAKMJD(',A,') --> ', F9.3, 3x, A )
        call flush(6)
      endif

c -----------------------------------------------

      LDMP_USER =  BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_DUMP)
      LDMP      = LDMP_USER

      IF ( LDMP ) THEN
        print*,'  --------------------------------------------- '
        print*,'  BEGIN DUMP of SET_PEAKMJD for SN ', CCID
        print*,'  '
        print*,'                  MJDat    SNRat      PKMJD  PKMJD  '
        print*,'  filt  FLUXMAX   FLUXMAX  FLUXMAX    fit    err    '
        print*,'  --------------------------------------------------'

        DO 660 ifilt_obs = 1, MXFILT_ALL
           if ( .not. USEFILT(ifilt_obs) ) goto 660
           cfilt =  filtdef_string(ifilt_obs:ifilt_obs)
           write(6,661) cfilt
     &       , FLUXMAX(ifilt_obs)
     &       , MJDatFLUXMAX(ifilt_obs)
     &       , SNRatFLUXMAX(ifilt_obs)
     &       , PKMJD_FIT(ifilt_obs)
     &       , PKMJD_ERR(ifilt_obs)
661        format( T5,A, T7,F10.1, F11.2, F6.1, F11.2, F7.2 )

660      CONTINUE
         print*, ' '

        if ( ifilt_snrmin .GT. 0 ) then
          cfilt =  filtdef_string(ifilt_snrmin:ifilt_snrmin)
        else
          cfilt = 'none'
        endif
        print*,'    Filter with min SNR at max: ', cfilt

        if ( ifilt_reject .GT. 0 ) then
          cfilt =  filtdef_string(ifilt_reject:ifilt_reject)
        else
          cfilt = 'none'
        endif
        print*,'    PKMJD-outlier filter rejected : ', cfilt

        print*,'    PEAKMJD(CALC,SEARCH)  = ',
     &            PKMJD, SNLC_SEARCH_PEAKMJD

        print*,'    CALC-SEARCH PKMJD DIF = ', DIF
        print*,'  END DUMP of SET_PEAKMJD for SN ', CCID
        print*,'  --------------------------------------------- '
      ENDIF

c -----------------------------------------
800   CONTINUE

      PKMJD = PKMJD + SHIFT_SETPKMJD
      SNLC_SNANAFIT_PEAKMJD = PKMJD
      SNLC_SEARCH_PEAKMJD   = PKMJD

      RETURN
      END  ! end SET_PEAKMJD


C =========================================
CDECK  ID>,  MNFIT_PKMJD. 
      SUBROUTINE MNFIT_PKMJD(ifilt_obs, FITWIN_MJD,
     &        FLUXatMAX, MJDatMAX, PKMJD,PKMJDERR, PKFLUX, PKFLUXERR )

c -----------------------------------------------
c Created Oct 29, 2009 by R.Kessler
c Fit FCNANYLC (any LC function) to estimate PKMJD.
c
c METHOD:
c First get  approx PEAKMJD = filter-average of MJDs at max flux.
c Then grid-minimize Eq. 1 of  Bazin et al., (SNLC CC rate)
c from astro-ph 0904.1066.
c
c               exp[ -(t-t0)/Tfall ]
c  f(t) = A * --------------------------  +  B
c              1 + exp[ -(t-t0)/Trise ]
c
c where t0, Trise, Tfall, A, & B=0 are the five
c fit-parameters for each filter. We only care about
c getting an approximate function, so we don't care
c about errors.
c
c Note that the exponent in their denomintor is missing a
c minus sign (with Trise > 0). The t0 parameter is not really
c the time at peak; after the fit has converged, the true Tpeak
c is found by setting the derivative=0.
c
c Jun 6, 2010: for POLYCOR option, do BTEST on OPT_SETPKMJD
c
c Oct 26, 2010: remove "SET PRint" command so that we get
c               correlation matrix printed to screen.
c
c Dec 9, 2011: keep track of min-error and  wgted error for
c              T0 and F0err/F0.
c
c May 28 2019: add FITWIN_MJD argument to restrict range of epochs fit.
c Sep 22 2020: MNARG -> MNARG(10) to avoid warnings with gcc v10
c ----------------------------

      IMPLICIT NONE

c function args

      INTEGER IFILT_OBS   ! (I) SN index and obs filter to fit

      REAL*8
     &   FITWIN_MJD(2) ! (I) MJD window to fit observations
     &  ,MJDatMAX      ! (I) MJD at epoch with max flux
     &  ,FLUXatMAX     ! (I) flux at MJD with max flux
     &  ,PKMJD      ! (O) MJD at peak of function
     &  ,PKMJDERR   ! (O) approx error on PKMJD (used for wgted avg)
     &  ,PKFLUX     ! (O) peak flux from fit
     &  ,PKFLUXERR  ! (O) error on above


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


c MINUIT stuff

      INTEGER IERR, IPAR, IVARBL

      INTEGER
     &   IUNIN, IUOUT, IUWRI
     &  ,NFIXPAR, IFILT

      EXTERNAL FCNANYLC, ANYLCFUN
      DOUBLE  PRECISION  ANYLCFUN

      LOGICAL USE_ANYFUN, USE_POLYCOR

      REAL*8
     &   MNARG(10)
     &  ,FIXLIST(NPAR_ANYLC)
     &  ,INIBND(2,NPAR_ANYLC)
     &  ,INISTP(NPAR_ANYLC)
     &  ,INIVAL(NPAR_ANYLC)
     &  ,TMPVAL(10), TMPERR(10), BND1, BND2
     &  ,T0, TRISE, TFALL, ARG, T0ERR
     &  ,INIVAL_TMP, COV
     &  ,ERRTMP

c functions
      REAL*8 COVPKFLUXFUN

C ---------------- BEGIN -------------

      USE_ANYFUN  = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_ANYFUN)
      USE_POLYCOR = BTEST(OPT_SETPKMJD,OPTBIT_SETPKMJD_POLYCOR)

      IUNIN = 5
      IUOUT = LUNPKMJD   ! write to file instead of STDOUT=6
      IUWRI = 7

      IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)

c ---------------------------------
c write header to log file so we know what CID and filter

      write(LUNPKMJD,20)
     &   SNLC_CCID
     &  ,filtdef_string(ifilt_obs:ifilt_obs)
20    format(/, T2, 60('#'),
     &       /, T10,'MNFIT_PKMJD for CID=',A8,' FILTER=',A,
     &       /, T2, 60('#'), / )

c ------------------------

      CALL MNINIT(IUNIN,IUOUT,IUWRI)  ! init MINUIT

      MNARG(1) = dble(0.0)
      CALL MNEXCM(FCNANYLC, 'SET NOWarnings', MNARG,0,IERR, ANYLCFUN)

      MNARG(1) = DBLE(MINUIT_PRINT_LEVEL)
      CALL MNEXCM(FCNANYLC, 'SET PRI', MNARG, 1, IERR, ANYLCFUN )


c init each parameter
      INIBND(1,IPAR_ISN) = 0
      INIBND(2,IPAR_ISN) = 9999999.
      INIVAL(IPAR_ISN)   = DBLE(SNLC_CID)
      INISTP(IPAR_ISN)   = 0.0       ! fixed parameter

      INIBND(1,IPAR_FILT) = 0
      INIBND(2,IPAR_FILT) = 100
      INIVAL(IPAR_FILT)   = DBLE(IFILT_OBS)
      INISTP(IPAR_FILT)   = 0.0     ! fixed parameter

      INIBND(1,IPAR_MJDMIN) = 0
      INIBND(2,IPAR_MJDMIN) = 150000
      INIVAL(IPAR_MJDMIN)   = FITWIN_MJD(1)
      INISTP(IPAR_MJDMIN)   = 0.0     ! fixed parameter

      INIBND(1,IPAR_MJDMAX) = 0
      INIBND(2,IPAR_MJDMAX) = 150000
      INIVAL(IPAR_MJDMAX)   = FITWIN_MJD(2)
      INISTP(IPAR_MJDMAX)   = 0.0     ! fixed parameter

      INIBND(1,IPAR_T0) = MJDatMAX - 50.0
      INIBND(2,IPAR_T0) = MJDatMAX + 50.0
      INIVAL(IPAR_T0)   = MJDatMAX
      INISTP(IPAR_T0)   = 2.0

      INIBND(1,IPAR_TRISE) =  1.0
      INIBND(2,IPAR_TRISE) =  40.
      INIVAL(IPAR_TRISE)   =  5.0
      INISTP(IPAR_TRISE)   =  2.0

      INIBND(1,IPAR_TFALL) = 1.0
      INIBND(2,IPAR_TFALL) = 100.0
      INIVAL(IPAR_TFALL)   = 10.0
      INISTP(IPAR_TFALL)   = 2.0

      INIBND(1,IPAR_A0) = FLUXatMAX * 0.2
      INIBND(2,IPAR_A0) = FLUXatMAX * 5.0
      INIVAL(IPAR_A0)   = FLUXatMAX * 1.2
      INISTP(IPAR_A0)   = FLUXatMAX * 0.1

      IF ( USE_POLYCOR ) THEN
         INIVAL_TMP = 0.1
      ELSE
         INIVAL_TMP = 0.0
      ENDIF

      INIBND(1,IPAR_A1)   = -20.0
      INIBND(2,IPAR_A1)   =  20.0
      INIVAL(IPAR_A1)     =   0.0
      INISTP(IPAR_A1)     = INIVAL_TMP

      INIBND(1,IPAR_A2)   = -20.0
      INIBND(2,IPAR_A2)   =  20.0
      INIVAL(IPAR_A2)     =   0.0
      INISTP(IPAR_A2)     = INIVAL_TMP
c      PKPARNAME(IPAR_A2)  =  'A2'


      CHI2_FITPKMJD(IFILT) = -9.0
      NDOF_FITPKMJD(IFILT) = -9

      NFIXPAR = 0
      DO IPAR = 1, NPAR_ANYLC

         CALL MNPARM(IPAR,    PKPARNAME(IPAR)
     &       ,INIVAL(IPAR),   INISTP(IPAR)
     &       ,INIBND(1,IPAR), INIBND(2,IPAR)
     &       ,IERR   )

         IF ( IERR .NE. 0 ) THEN
            WRITE (6,'(A,A10,A)') '  ERROR initializing ',
     &            PKPARNAME(ipar), '  with MNPARM '
            RETURN
         ENDIF

c keep track of fixed parameters
        if ( INISTP(IPAR) .EQ. 0.0 ) then
           NFIXPAR =  NFIXPAR + 1
           FIXLIST(NFIXPAR) = DBLE ( IPAR )
        endif

      ENDDO  ! end of IPAR loop

      CALL FLUSH(6)

      CALL MNEXCM(FCNANYLC, 'FIX', FIXLIST, NFIXPAR, IERR, ANYLCFUN )

      MNARG(1) = dble(30000.0)  ! MAXCALLS
      CALL MNEXCM(FCNANYLC, 'MINIMIZE', MNARG, 0, IERR, ANYLCFUN )

      DO IPAR = 1,  NPAR_ANYLC

        CALL MNPOUT(  IPAR, PKPARNAME(IPAR)
     &              , TMPVAL(IPAR), TMPERR(IPAR)
     &              , BND1, BND2, IVARBL )

        SNLC_SNANAFIT_PEAKMJD_FITPAR(ifilt,ipar) = SNGL(TMPVAL(IPAR))
        SNLC_SNANAFIT_PEAKMJD_FITERR(ifilt,ipar) = SNGL(TMPERR(IPAR))

      ENDDO

      MNARG(1) = ZERO8
      CALL MNEXCM ( FCNANYLC, 'EXIT',  MNARG, 0, IERR, ANYLCFUN )
**      PRINT *,'  MNFIT_PKMJD: EXIT returns IERR = ', IERR

c compute PKMJD from setting 1st deriviate = 0
      Tfall = TMPVAL(IPAR_TFALL)
      Trise = TMPVAL(IPAR_TRISE)
      T0    = TMPVAL(IPAR_T0)
      T0ERR = TMPERR(IPAR_T0)

      arg = (Tfall - Trise)/Trise
      if ( ARG .GT. 0.1 ) then
         PKMJD = T0 + Trise * DLOG(ARG)
         PKMJDERR = MIN(T0ERR,4.0)  ! max error is 4 days
      else
         PKMJD = MJDatMAX
         PKMJDERR = 4.0
      endif


      if ( OPT_REFORMAT_SALT2 .GT. 0 ) then
         PKMJDERR = T0ERR
      endif

c get error on peak flux from fit


      CALL MNEMAT(FITERRMAT_PKMJD(1,1,ifilt_obs),NPAR_ANYLC)
      COV = COVPKFLUXFUN(ifilt_obs,PKMJD,PKMJD)

      PKFLUX    = ANYLCFUN(PKMJD,TMPVAL)
      PKFLUXERR = SQRT(COV)

c Dec 9, 2011
c keep track of min error and wgted error
      ERRTMP  = T0ERR
      IF ( ERRTMP .LT. PKMJD_ERRMIN .and. ERRTMP .GT. 0.0 ) THEN
         PKMJD_ERRMIN = SNGL(ERRTMP)
         PKMJD_ERRWGT = PKMJD_ERRWGT + 1.0/SNGL(ERRTMP*ERRTMP)
      ENDIF

      ERRTMP  = PKFLUXERR/PKFLUX
      IF ( ERRTMP .LT. PKFLUX_ERRMIN .and.
     &     ERRTMP .GT. 0.0   .and.
     &     ERRTMP .NE. 1.0 ) THEN
        PKFLUX_ERRMIN = SNGL(ERRTMP)
        PKFLUX_ERRWGT = PKFLUX_ERRWGT + 1.0/SNGL(ERRTMP*ERRTMP)
      ENDIF

      RETURN
      END

C =========================================
CDECK  ID>,  FCNANYLC. 
      SUBROUTINE FCNANYLC(NVAR,GRAD,CHI2,XVAL,IFLAG, ANYLCFUN )
c
c Created Oct 25, 2009
c MINUIT-callable function to return data-model CHI2
c using the "ANY LC" model from Bazin et al.
c See comments at top of MNFIT_PKMJD.
c
c May 28, 2019: Use MJDMIN/MJDMAX to restrict epoch range.
c
c --------------------------------------------
      IMPLICIT NONE

      INTEGER NVAR, IFLAG
      REAL*8
     &   XVAL(*)  ! (I) T0, Trise, Tfall, A, B
     &  ,GRAD(*)
     &  ,CHI2
     &  ,ANYLCFUN

      EXTERNAL ANYLCFUN


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,PKMJDCOM.  Oct 2014 inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


c local var

      INTEGER
     &   ISN, IFILT_OBS, IFILT
     &  ,NEWMJD, EPMIN, EPMAX, EP, NDOF

      REAL*8
     &   MJDMIN, MJDMAX, FLUX, FLUXERR, MJD, SQDIF, SQERR, SNR
     &  ,MODEL_FLUX, MODEL_FLUXERR

      REAL*8 MODEL_MAGERR
      PARAMETER ( MODEL_MAGERR = 0.05 )

C --------------- BEGIN -------------

      ISN         = INT ( XVAL(1) + 0.0001 )
      IFILT_OBS   = INT ( XVAL(2) + 0.0001 )
      MJDMIN      = XVAL(3)
      MJDMAX      = XVAL(4)

      CHI2 = 0.0
      NDOF = 0

      DO 200 NEWMJD = 1, ISNLC_NEWMJD_STORE

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,NEWMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,NEWMJD)
        MJD   = SNLC8_MJD(EPMIN)

        if ( MJD < MJDMIN ) goto 200
        if ( MJD > MJDMAX ) goto 200

        MODEL_FLUX    = ANYLCFUN(MJD,XVAL)
        MODEL_FLUXERR = MODEL_FLUX * MODEL_MAGERR

        DO 201 EP = EPMIN, EPMAX

            if ( IFILT_OBS .NE. ISNLC_IFILT_OBS(ep) ) GOTO 201

            FLUX      = SNLC_FLUXCAL(ep)
            FLUXERR   = SNLC_FLUXCAL_ERRTOT(ep)

c SNR requirement makes things worse ??
            SNR = FLUX/FLUXERR

            SQDIF = (FLUX - MODEL_FLUX)**2
            SQERR = FLUXERR*FLUXERR + MODEL_FLUXERR*MODEL_FLUXERR
            CHI2  = CHI2 + SQDIF/SQERR
            NDOF = NDOF + 1

201     CONTINUE   ! ep
200   CONTINUE  ! end of NEWMJD

c --------------------------------------
c load chi2 and NDOF in global array

      IF (IFLAG == FCNFLAG_LAST ) THEN
        IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
        CHI2_FITPKMJD(IFILT) = SNGL(CHI2)
        NDOF_FITPKMJD(IFILT) = NDOF
      ENDIF

      RETURN
      END

C ======================================
CDECK  ID>,  ANYLCFUN. 
      DOUBLE PRECISION FUNCTION ANYLCFUN(MJD,XVAL)
c
c Created Dec 5, 2009 by R.Kessler
c Any light curve function based on Bazin et al,, 2009 (SNLS CC rate)
c
c May 28 2019: replace hard-code XVAL-indices with IPAR_XXX
c ------------
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


c function args

      REAL*8 MJD, XVAL(*)

c local args

      REAL*8
     &   T0, TRISE, TFALL, A0, A1, A2
     &  ,ARG1, ARG2, DUM1, DUM2, TDIF, POLYCOR
     &  ,MODEL_FLUX

C ---------- BEGIN ---------

      T0    = XVAL(IPAR_T0)
      TRISE = XVAL(IPAR_TRISE)
      TFALL = XVAL(IPAR_TFALL)
      A0    = XVAL(IPAR_A0)
      A1    = XVAL(IPAR_A1)
      A2    = XVAL(IPAR_A2)

      TDIF  = MJD - T0

c numerator
      ARG1  = TDIF / Tfall
      DUM1  = EXP(-ARG1)

c denominator
      ARG2  = TDIF / Trise
      DUM2  = 1.0 + EXP(-ARG2)

c polynominal correction
      POLYCOR = A0 * ( 1.0 + A1*TDIF + A2*TDIF*TDIF )

c final flux

      MODEL_FLUX = POLYCOR * (DUM1/DUM2)

c Aug 31 2019: protect against crazy values.
      if ( MODEL_FLUX > +1.0E20 ) MODEL_FLUX =  1.0E20
      if ( MODEL_FLUX < -1.0E20 ) MODEL_FLUX = -1.0E20

      ANYLCFUN = MODEL_FLUX

      RETURN
      END

C =====================================
CDECK  ID>,  COVPKFLUX. 
      REAL*8 FUNCTION COVPKFLUXFUN(ifilt_obs, MJD1, MJD2)

c
c Created April 12, 2010 by R.Kessler
c
c Similar to COVARFLUX in snlc_fit.car, but this is
c for the PKMJD fit to estimate error on peak flux.
c Since the user-function calls are different than
c in snlc_fit.car, we must have a separate COV function
c here to evaluate errors.
c
c Using full fitpar covariance, FITERRMAT(ipar1,ipar2)
c  ( see eq. 32.24 in PDG statistics section)
c
c                           dF1   dF2
c U12       = \sum_{k,l}  ------ ------ * FITERRMAT_PKMJD(k,l)
c                         dPAR_k dPAR_l
c
c  where PAR_k = fit-parameter with index 'k'.
c  and F1,F2 are fluxes at days with index 1,2.
c
c If T1 = T2,  then U12 = square of model
c uncertainty at this epoch.
c
c
c
c Jan 9, 2012: fix bug : use IFILT in SNLC_SNANAFIT_PEAKMJD_FITPAR
c -------------------------------

      IMPLICIT NONE

c subroutine args:

      INTEGER
     &   IFILT_OBS  ! (I) ifilt_obs

      REAL*8  MJD1, MJD2  ! (I) MJDs to get covariance

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,PKMJDCOM. inserted below by ypatchy. 

c define bits for user option-mask OPT_SETPKMJD  (lsb = 0 )
      INTEGER
     &   OPTBIT_SETPKMJD_ANYFUN
     &  ,OPTBIT_SETPKMJD_POLYCOR
     &  ,OPTBIT_SETPKMJD_NOABORT
     &  ,OPTBIT_SETPKMJD_FLUXMAX
     &  ,OPTBIT_SETPKMJD_SAVEPAR
     &  ,OPTBIT_SETPKMJD_FLUXMAX2
     &  ,OPTBIT_SETPKMJD_FLUXMAX3
     &  ,OPTBIT_SETPKMJD_TRIGGER
     &  ,OPTBIT_SETPKMJD_DUMP
     &  ,OPTBIT_SETPKMJD_SIM

      PARAMETER (
     &  OPTBIT_SETPKMJD_ANYFUN  = 0  ! (=1) use exact function from Bazin 09
     & ,OPTBIT_SETPKMJD_POLYCOR = 1  ! (=2) include POLY cor in Bazin function
     & ,OPTBIT_SETPKMJD_NOABORT = 2  ! (=4) do not abort if can't find PKMJD
     & ,OPTBIT_SETPKMJD_FLUXMAX = 3  ! (=8) PEAKMJD=MJD(maxFlux) like JG
     & ,OPTBIT_SETPKMJD_FLUXMAX2= 4  ! (=16) PKMJD for Fmax clump
     & ,OPTBIT_SETPKMJD_FLUXMAX3= 5  ! (=32) idem, but log10(SNR) weight
     & ,OPTBIT_SETPKMJD_TRIGGER = 6  ! (=64) PKMJD = MJD_TRIGGER
     & ,OPTBIT_SETPKMJD_SAVEPAR = 9  ! (=512) save fit params to SNANA table
     & ,OPTBIT_SETPKMJD_DUMP    =10  !(=1024) extra screen dump per SN/filter
     & ,OPTBIT_SETPKMJD_SIM     =11  !(=2048) PKMJDINI = SIM_PEAKMJD
     &   )

c Define fit params

      INTEGER
     &   IPAR_ISN, IPAR_FILT, IPAR_MJDMIN, IPAR_MJDMAX
     &  ,IPAR_T0, IPAR_TRISE, IPAR_TFALL
     &  ,IPAR_A0, IPAR_A1, IPAR_A2

      REAL SNRMIN_forFLUXMAX

      PARAMETER (
     &   IPAR_ISN    = 1  ! fixed param
     &  ,IPAR_FILT   = 2  ! fixed param
     &  ,IPAR_MJDMIN = 3  ! fixed param (May 2019)
     &  ,IPAR_MJDMAX = 4  ! fixed param (May 2019)
     &  ,IPAR_T0     = 5
     &  ,IPAR_TRISE  = 6
     &  ,IPAR_TFALL  = 7
     &  ,IPAR_A0     = 8
     &  ,IPAR_A1     = 9
     &  ,IPAR_A2     = 10
     &  ,SNRMIN_forFLUXMAX  = 3.0   ! min SNR to consider for fluxmax
     &     )

       CHARACTER  PKPARNAME(NPAR_ANYLC)*16
       DATA  PKPARNAME /
     &     'ISN', 'IFILTOBS', 'MJDMIN', 'MJDMAX',
     &     'T0', 'TRISE', 'TFALL','A0', 'A1', 'A2' /

c -----
      REAL*8 FITERRMAT_PKMJD(NPAR_ANYLC,NPAR_ANYLC,MXFILT_ALL)

      COMMON / PKMJDCOM8 / FITERRMAT_PKMJD

      REAL*4
     &   PKMJD_FIT(MXFILT_ALL)
     &  ,PKMJD_ERR(MXFILT_ALL)
     &  ,PKMJD_ERRMIN, PKMJD_ERRWGT  ! min and weighted error
     &  ,PKFLUX_FIT(MXFILT_ALL)
     &  ,PKFLUX_ERR(MXFILT_ALL)
     &  ,PKFLUX_ERRMIN, PKFLUX_ERRWGT  ! min and weighted error
     &  ,CHI2_FITPKMJD(MXFILT_ALL)

      INTEGER NFIT_PKMJD, NDOF_FITPKMJD(MXFILT_ALL)

      COMMON / PKMJDCOM4 /
     &   PKMJD_FIT, PKMJD_ERR, PKMJD_ERRMIN, PKMJD_ERRWGT
     &  ,PKFLUX_FIT, PKFLUX_ERR, PKFLUX_ERRMIN, PKFLUX_ERRWGT
     &  ,NFIT_PKMJD
     &  ,CHI2_FITPKMJD, NDOF_FITPKMJD


      INTEGER
     &   ipar, ipar_k, ipar_l, isp_k, isp_l, IFILT

      REAL*8
     &   XVAL(NPAR_ANYLC), XERR(NPAR_ANYLC)
     &  ,FLUX1, FLUX2
     &  ,FTMP1, FTMP2
     &  ,SAVEVAL_k, SAVEVAL_l
     &  ,ERRPAR_k,  ERRPAR_l
     &  ,dF1dVAL_k, dF2dVAL_l, FF
     &  ,V_kl, U12

c functions
      REAL*8  ANYLCFUN

C -------------- BEGIN -------------

      COVPKFLUXFUN = 0.0
      U12 = 0.0   ! init output

c get reference fluxes to computer deriviates below.

      IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
      DO ipar = 1, NPAR_ANYLC
        XVAL(ipar) = SNLC_SNANAFIT_PEAKMJD_FITPAR(ifilt,ipar)
        XERR(ipar) = SNLC_SNANAFIT_PEAKMJD_FITERR(ifilt,ipar)
      ENDDO
      Flux1   =  ANYLCFUN ( MJD1, XVAL )
      Flux2   =  ANYLCFUN ( MJD2, XVAL )

      isp_k = 0
      DO 301 ipar_k = 1, NPAR_ANYLC
         IF ( XERR(ipar_k) .LE. 0.0 ) goto 301
         isp_k = isp_k + 1  ! for COV matrix

      isp_l = 0
      DO 302 ipar_l = 1, NPAR_ANYLC
         IF ( XERR(ipar_l) .LE. 0.0 ) goto 302
         isp_l = isp_l + 1 ! for COV matrix

         SAVEVAL_k = XVAL(ipar_k)
         SAVEVAL_l = XVAL(ipar_l)

         ERRPAR_k  = XERR(ipar_k)
         ERRPAR_l  = XERR(ipar_l)

c change fitpar values by +1 sigma and re-evaluate Flux.

         XVAL(ipar_k) = XVAL(ipar_k) + ERRPAR_k
         Ftmp1  = ANYLCFUN ( MJD1, XVAL )
         XVAL(ipar_k) = SAVEVAL_k

c repeat for 2nd fitpar ...
         XVAL(ipar_l) = XVAL(ipar_l) + ERRPAR_l
         Ftmp2   = ANYLCFUN ( MJD2, XVAL )
         XVAL(ipar_l) = SAVEVAL_l

c make sure that errors are non-zero before dividing.

         c2err = ' '
         if ( ERRPAR_k .EQ. 0.0 ) then
           write(c1err,662) PARNAME_STORE(ipar_k)
           CALL MADABORT("COVPKFLUXFUN", c1err, c2err )
         endif
         if ( ERRPAR_l .EQ. 0.0 ) then
           write(c1err,662) PARNAME_STORE(ipar_l)
           CALL MADABORT("COVPKFLUXFUN", c1err, c2err )
         endif
662      format('Cannot compute FLUXERR with ERR(',A,') = 0' )

c evaluate partial deriviates for flux
         dF1dVAL_k = (Ftmp1 - Flux1) / ERRPAR_k
         dF2dVAL_l = (Ftmp2 - Flux2) / ERRPAR_l

         FF   = dF1dVAL_k * dF2dVAL_l
         V_kl = FITERRMAT_PKMJD(isp_k,isp_l,ifilt_obs)
         U12 = U12 + FF * V_kl

c         print*,'  xxxx V_(',ipar_k,ipar_l, ') = ', V_kl,
c     &      '   RHO=', V_kl/(ERRPAR_k*ERRPAR_l)

302   CONTINUE
301   CONTINUE

      COVPKFLUXFUN = U12

      RETURN
      END

C ============================
CDECK  ID>,  INTERPANYLC. 
      SUBROUTINE SNMJD_INTERP_ANYLC(ifilt_obs)
c
c
c Jan 9, 2012: write output to LUNINTERP if SNMJD_OUT_FILE is defined.
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


      INTEGER ifilt_obs   ! (I) absolute filter index

c local args

      INTEGER  NMJD, imjd,  LENCCID, ipar, IFILT, LUN

      REAL*8
     &   FLUX, FLUXERR, MJD, COV, MJDLIST(MXINTERP)
     &  ,XVAL(NPAR_ANYLC)
     &  ,XERR(NPAR_ANYLC)

      CHARACTER cfilt*1, ccid*(MXCHAR_CCID)

      LOGICAL ADDFLAG  ! dummy arg

c functions
      REAL*8 COVPKFLUXFUN, ANYLCFUN

C ---------------- BEGIN --------------

      IF ( N_INTERP_MJDLIST .LE. 0 ) RETURN

      CCID = SNLC_CCID
      LENCCID = INDEX(CCID,' ') - 1

c get NMJD and MJDLIST;
      CALL GET_INTERP_MJDLIST(CCID, NMJD, MJDLIST, ADDFLAG)

      IF ( NMJD .EQ. 0 ) RETURN

      IFILT     = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
      cfilt     = filtdef_string(ifilt_obs:ifilt_obs)

      IF ( SNMJD_OUT_FILE .EQ. ' ' ) THEN
         LUN = -1
      ELSE
         LUN = LUNINTERP
      ENDIF

      DO 200 imjd = 1, NMJD

        MJD  = MJDLIST(imjd)

c IF MJD=0, then replace with PEAKMJD (Aug 20, 2012)
        IF ( MJD .LT. 1.0  ) THEN
            MJD = SNLC_SEARCH_PEAKMJD
        ENDIF

        DO ipar = 1, NPAR_ANYLC
          XVAL(ipar) = SNLC_SNANAFIT_PEAKMJD_FITPAR(ifilt,ipar)
          XERR(ipar) = SNLC_SNANAFIT_PEAKMJD_FITERR(ifilt,ipar)
        ENDDO

        COV     = COVPKFLUXFUN(ifilt_obs,MJD,MJD)
        FLUX    = ANYLCFUN(MJD,XVAL)
        FLUXERR = SQRT(COV)

        write(6,60) SNLC_CCID(1:LENCCID),
     &       cfilt, MJD, FLUX, FLUXERR
60      format(T4,'INTERP-FLUX(CID=',A, '-', A,
     &         ' MJD=', F9.3, ')= ', G10.4, ' +- ', G10.4 )

        IF ( LUN .GT. 0 ) THEN
           write(LUN,70) SNLC_CCID(1:12),
     &       cfilt, MJD, FLUX, FLUXERR
70         format('INTERP:',2x, A, 2x,A, 3x, F9.3, 2x, G12.4, G12.4)
        ENDIF

200   CONTINUE

      RETURN
      END  ! end of SNMJD_INTERP_ANYLC

C ======================

C =======================
CDECK  ID>,  MNFIT_DRIVER. 
      SUBROUTINE MNFIT_DRIVER (
     &   CID         ! (I) cand id
     &  ,NFITPAR     ! (I) number of fit parameters
     &  ,INIVAL      ! (I) initial parmater values
     &  ,INISTP      ! (I) initial step sizes (0=> fixed parameter)
     &  ,INIBND      ! (I) parameter bounds (0,0 => no bound)
     &  ,PARNAME     ! (I) list of parmater names
     &  ,USE_MINOS   ! (I) T=> use minos
     &  ,PRINT_LEVEL ! (I) integer print level (-1=none)
     &  ,FITVAL       ! (O) final fit values
     &  ,FITERR_PLUS  ! (O) final fit errors, positive
     &  ,FITERR_MINUS ! (O) final fit errors, negative
     &  ,FITCHI2      ! (O) min chi2
     &  ,NFIXPAR      ! (O) number of fixed parameters
     &  ,ERRTYPE      ! (O) error types (MINOS vs. PARABOLIC)
     &  ,MNSTAT_COV   ! (O) status of cov matrix (see minuit manual)
     &  ,IERR         ! (O) 0=>OK
     &      )
c
c Created 2 Feb 28, 2006 by D.Cinabro and R.Kessler
c
c Interface for minuit fitting
C
c This is a SNANA routine ... not a MINUIT routine
C
C Note that the non-integer/characater inputs are Double Precision!!!!
C For more information on using MINUIT, type minuit in Google and follor
c the URL with cern in it.
c
c
c Aug 31,  2009: Add USE_MINOS argument.
c
c May 21, 2012: set print level using SNLCINP namelist MINUIT_PRINT_LEVEL
c
c Jan 03 2016: pass new output arg MNSTAT_COV
c Apr 19 2022: set DO_PRINT for printing to suppress STDOUT for batch jobs
c
c -------------------------------------------------

      IMPLICIT NONE

c arguments

      INTEGER CID, NFITPAR, NFIXPAR, PRINT_LEVEL

      LOGICAL USE_MINOS  ! (I)

      DOUBLE PRECISION
     &   INIVAL(NFITPAR)
     &  ,INISTP(NFITPAR)
     &  ,INIBND(2,NFITPAR)      ! (I) fit bounds (zero=> no bound)
     &  ,FITVAL(NFITPAR)        ! (O) final fit values
     &  ,FITERR_PLUS(NFITPAR)   ! (O) final fit errors
     &  ,FITERR_MINUS(NFITPAR)  ! (O) final fit errors
     &  ,FITCHI2                ! (O) min chi2 value

      CHARACTER PARNAME(NFITPAR)*20  ! (MXCHAR_PARNAME)

      INTEGER ERRTYPE(NFITPAR), MNSTAT_COV
      INTEGER IERR

c local var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNCONTCM. inserted below by ypatchy. 

      INTEGER  MXPLOT_CONT, MXBIN_CONT
      PARAMETER (
     &   MXPLOT_CONT  = 5    ! max number of contour plots per SN
     &  ,MXBIN_CONT   = 100  ! max number of contour bins
     &     )

c define arrays to hold MNCONT informatino for contour plots

      INTEGER
     &   NPLOT_CONT                 ! number of user-contour plots
     &  ,HID_CONT(2,MXPLOT_CONT)    ! store hbook ids for vectors
     &  ,IPAR_CONT(2,MXPLOT_CONT)   ! stores which IPAR for contours
     &  ,NPT_CONT(MXPLOT_CONT)      ! stores Npt per contour plot
     &  ,NPT_FOUND(MXPLOT_CONT)

      REAL*8
     &   VCONT8(MXBIN_CONT,2,MXPLOT_CONT)  ! vector array for IPAR1

      COMMON / CONTOURCOM4 / NPLOT_CONT
     &   ,HID_CONT, IPAR_CONT, NPT_CONT, NPT_FOUND

      COMMON / CONTOURCOM8 /  VCONT8



      EXTERNAL FCNSNLC, USRFUN
      DOUBLE PRECISION  USRFUN

      INTEGER
     &   IPAR, IVARBL, i, IFLAG, NARG
     &  ,NPARI, NPARX, ISTAT

      DOUBLE PRECISION
     &   FIXLIST(NFITPAR)
     &  ,BND1, BND2
     &  ,STRATEGY(4), PARG(4)
     &  ,MAXCALLS(4)
     &  ,GRAD(NFITPAR)
     &  ,CHI2
     &  ,ARGLIST(20)
     &  ,EPLUS, EMINUS, EPARAB, GLOBCC
     &  ,FEDM, ERRDEF
     &  ,ERRSYM      ! local SYMMMETRIC fiterr

      LOGICAL LFIX, DO_PRINT

C Unit numbers for input and output

      INTEGER IUNIN,IUOUT,IUWRI
      DATA IUNIN/5/
      DATA IUOUT/6/
      DATA IUWRI/7/

C -------------------- BEGIN -------------------------

      IERR = 0
      NFIXPAR = 0
      FITCHI2 = 0.0
      DO_PRINT = STDOUT_UPDATE
C
C Initialize MINUIT, input unit, output unit, save unit
C

      CALL MNINIT(IUNIN,IUOUT,IUWRI)

      PARG(1) = DBLE(PRINT_LEVEL)
      CALL MNEXCM(FCNSNLC, 'SET PRI', PARG, 1, IERR, USRFUN )

C Define parameters in MINUIT

      DO IPAR = 1, NFITPAR

         CALL MNPARM(IPAR, PARNAME(IPAR)
     &       ,INIVAL(IPAR), INISTP(IPAR)
     &       ,INIBND(1,IPAR)   ! lo-bound
     &       ,INIBND(2,IPAR)   ! hi-bound
     &       ,IERR   )
         IF ( IERR .NE. 0 ) THEN
            WRITE (6,'(A,A10,A)') '  ERROR initializing ',
     &            PARNAME(ipar), '  with MNPARM '
            RETURN
         ENDIF

c init fit params
         FITVAL(ipar)       = 0.0
         FITERR_PLUS(ipar)  = 0.0
         FITERR_MINUS(ipar) = 0.0
         ERRTYPE(ipar)      = 0

C Set list of fixed parameters with step size = 0

         IF ( INISTP(IPAR) .EQ. 0.0 ) THEN
            NFIXPAR = NFIXPAR + 1
            FIXLIST(NFIXPAR) = DFLOAT(IPAR)
         ENDIF

      ENDDO

      CALL FLUSH(6)

c --------------------------------------------
c fix param if its step size is zero

      IF ( NFIXPAR .GT. 0 ) THEN

         CALL MNEXCM(FCNSNLC,'FIX',FIXLIST, NFIXPAR,IERR,USRFUN)
         IF ( IERR .NE. 0 ) THEN
            WRITE (6,'(A)') '  ERROR fixing parameters'
            RETURN
         ENDIF
      ENDIF

c call FCN function with init flag: IFLAG=2
      IFLAG = 2
      CALL FCNSNLC ( NFITPAR, GRAD, chi2, FITVAL, IFLAG, USRFUN )

C Set Strategy 2 for more accurate derivative calculation

      NARG = 1
      STRATEGY(1) = DBLE(2.0)   ! 1=default,  2 => better results

      IF ( DO_PRINT ) THEN
        print*,'  Set MINUIT STRATEGY = ', int(STRATEGY(1))
      ENDIF

      CALL MNEXCM(FCNSNLC,'SET STR', STRATEGY, NARG, IERR, USRFUN )
      MAXCALLS(1) = dble(30000.0)

C Actually do the fit

      IF ( DO_PRINT ) THEN
        PRINT *,' '
        PRINT *,' ------------------------------------------------ '
      ENDIF

      IF ( USE_MINOS ) THEN
        CALL MNEXCM(FCNSNLC, 'MINOS', MAXCALLS, NARG, IERR, USRFUN)
        IF ( DO_PRINT ) THEN
          PRINT *,'  MNFIT_DRIVER: MINOS returns IERR = ', IERR
        ENDIF
      ELSE
        CALL MNEXCM(FCNSNLC, 'MINIMIZE', MAXCALLS, 0, IERR, USRFUN)
        IF ( DO_PRINT ) THEN
          PRINT *,'  MNFIT_DRIVER: MIGRAD returns IERR = ', IERR
        ENDIF
      ENDIF

      IF ( DO_PRINT ) THEN
         PRINT *,' ------------------------------------------------ '
      ENDIF

c -------------------------------------------
c get the fit result

      IF ( DO_PRINT ) THEN
        PRINT *,' '
        PRINT *,'   MNFIT_DRIVER: extract fit parameters with MNPOUT'
        CALL FLUSH(6)
      ENDIF

      DO 44 IPAR = 1, NFITPAR

        LFIX = ( INISTP(ipar) .EQ. 0.0 )

        CALL MNPOUT(  IPAR, PARNAME(IPAR)
     &              , FITVAL(IPAR), ERRSYM
     &              , BND1,BND2, IVARBL )

        CALL MNERRS( IPAR, EPLUS, EMINUS, EPARAB, GLOBCC )

c xxxxxxxxxxxxxxxxxxxxxxxx
c        print*, IPAR, ': ERR(EPARAB)=', sngl(EPARAB)
c     &            ,'  ERR(+-) = ', sngl(EPLUS), sngl(EMINUS)
c xxxxxxxxxxxxxxxxxxxxxxxxxxxxx

c take average of +- errors (note that EMINUS is negative)
c If MINOS errors are zero, then use parabolic error above.

        if ( EPLUS .GT. 0.0 .and. EMINUS .LT. 0.0 ) THEN
           FITERR_PLUS(IPAR)   = EPLUS
           FITERR_MINUS(IPAR)  = EMINUS
           ERRTYPE(ipar)       = ERRTYPE_MINOS
        else
           FITERR_PLUS(IPAR)   = +ERRSYM
           FITERR_MINUS(IPAR)  = -ERRSYM
           ERRTYPE(ipar)       = ERRTYPE_PARAB
        endif

44    CONTINUE  ! end of loop over IPAR


c -------------------------------------------------------
c get chi2 and status; fill FITCHI2 return arg
c From Minuit manual, here are the ISTAT values from MNSTAT:
c
c ISTAT  meaning
c  0    Not calculated at all
c  1    Diagonal approximation only, not accurate
c  2    Full matrix, but forced positive-definite
c  3    Full accurate covariance matrix
c          (After MIGRAD, this is the indication of normal convergence.)

      CALL MNSTAT(FITCHI2, FEDM, ERRDEF, NPARI, NPARX, ISTAT)
      MNSTAT_COV = ISTAT  ! 3=OK

c ----------------------------------
c Prepare contours

      DO i = 1, NPLOT_CONT

         CALL MNCONT ( FCNSNLC
     &       , IPAR_CONT(1,i)  ! (I) 1st parameter for contour
     &       , IPAR_CONT(2,i)  ! (I) 2nd param
     &       , NPT_CONT(i)     ! (I) number of contour points
     &       , VCONT8(1,1,i)   ! (O) par1 contour array
     &       , VCONT8(1,2,i)   ! (O) par2 contour array
     &       , NPT_FOUND(i)    ! (O)
     &       , USRFUN )

      ENDDO

c Stop fit and make LAST call to function

      PARG(1) = 0.0
      CALL MNEXCM(FCNSNLC, 'EXIT',  PARG, 0, IERR, USRFUN )
      IF ( DO_PRINT ) THEN
        PRINT *,'  MNFIT_DRIVER: EXIT returns IERR = ', IERR
        CALL FLUSH(6)
      ENDIF

c ---------------------------------
      RETURN
      END  ! end MNFIT_DRIVER

C ===========================
CDECK  ID>,  MNFIT_STOREPAR. 
      SUBROUTINE MNFIT_STOREPAR(iter,IERR)
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

c
c Nov 17, 2011: replace CERNLIB's PROB with snana's PROB_CHI2NDOF
c Jan 04, 2016: protect sqrt(negative SQERR8)
c May 05, 2018: init FITERRMAT=0 instead of -9. Allows USESIM_xxx=T
c May 23, 2018: set LCFRACERRDIF_STORE(ipar)
c Feb 22, 2020: set NDOF_PRIOR=0  here on each iteration.
c
c subroutine args

      INTEGER
     &   iter   ! (I) iterationn
     &  ,IERR   ! (O) error flag; 0=> OK

c local variables

      INTEGER ipar, NDOF, ipar1, ipar2, i
      INTEGER J, JPAR(MXFITPAR), J1, J2, etmp
      REAL EPLUS, EMINUS, PCHI2
      LOGICAL LBADERR, FLOATBOTH

      REAL*8
     &   CHI8, GRAD8(MXFITPAR)
     &  ,EMAT8, ERR8(2), SQERR8(2), ERR_FINAL, ERR_LAST, ERR_AVG

c function

      REAL*8   PROB_CHI2NDOF
      REAL*8   USRFUN
      EXTERNAL USRFUN

C -------------- BEGIN ------------------

      IERR = 0   ! set output flag to OK

c store chi2

      FITCHI2_STORE(1)     = FITCHI2_MIN ! total chi2

c get prior-chi2 using special flag

      CALL FCNSNLC(NFITPAR_MN, GRAD8, CHI8, FITVAL(1,iter),
     &       FCNFLAG_PRIOR_ONLY, USRFUN)

c determine effective Ndof for prior.

      if ( CHI8 .GT. 0.01 ) then
        NDOF_PRIOR = 1
      else
        NDOF_PRIOR = 0
      endif

      FITCHI2_STORE(3) = CHI8  ! prior chi2
      FITCHI2_STORE(2) =
     &     FITCHI2_STORE(1) - FITCHI2_STORE(3)  ! total - prior

c store chi2 from ln(sigma) terms
      CALL FCNSNLC(NFITPAR_MN, GRAD8, CHI8, FITVAL(1,iter),
     &       FCNFLAG_SIGMA_ONLY, USRFUN)
      FITCHI2_STORE(4) = CHI8

c store number of degrees of freedom

      NDOF          = NEPOCH_FIT(0) - (NFITPAR_MN - NFIXPAR)
      NDOF_STORE(1) = NDOF + NDOF_PRIOR  ! full chi2
      NDOF_STORE(2) = NDOF               ! chi2 excluding prior
      NDOF_STORE(3) = NDOF_PRIOR         ! prior chi2 only
      NDOF_STORE(4) = 1                  ! ln(sigma)

c Convert fitchi2 into fitprobs.

      DO i     = 1, 4
        NDOF   = NDOF_STORE(i)
        CHI8   = DBLE(FITCHI2_STORE(i))

        if ( NDOF .GT. 0 .and. CHI8 .GT. 0.0 ) THEN
           PCHI2  = SNGL( PROB_CHI2NDOF(CHI8,NDOF) )
        ELSE
           PCHI2  = 1.0
        ENDIF

        FITPROBCHI2_STORE(i) = PCHI2
        LCCHI2_STORE(i)      = FITCHI2_STORE(i)
        LCPROBCHI2_STORE(i)  = FITPROBCHI2_STORE(i)
      ENDDO


c now store fit parameters.

      DO 444 ipar = 1, NFITPAR_MN

         FLOATPAR(ipar) = ( INISTP(ipar) .NE. 0.0 )

c if there are no floated params, then set errors
c to user-initialized values: FITERR(ipar)

         if ( NFIXPAR .EQ. NFITPAR_MN  ) then
           FITERR_PLUS(ipar,iter)   = FITERR(ipar,iter)
           FITERR_MINUS(ipar,iter)  = FITERR(ipar,iter)
         endif

         EPLUS  = FITERR_PLUS(ipar,iter)
         EMINUS = ABS ( FITERR_MINUS(ipar,iter) )

c if fit error is way too small, set error to INISTP
c and set error type to BAD

         LBADERR = Eplus  .LT. ERRMAX_BAD(ipar)
     &     .and.   Eminus .LT. ERRMAX_BAD(ipar)

c 9/22/2007: allow tiny errors when the exposure time is large.
         IF ( SIM_EXPOSURE_TIME(1) .GT. 10.0 ) then
            LBADERR = .FALSE.
         endif

c set bad-error flag of fit-value has not moved from initial value.
         LBADERR = LBADERR .or.
     &            ( INIVAL(ipar) .EQ. FITVAL(ipar,iter) )

         if ( FLOATPAR(ipar) .and. LBADERR ) then
            FITERR_PLUS(ipar,iter)  = +INISTP(ipar)
            FITERR_MINUS(ipar,iter) = -INISTP(ipar)
            EPLUS              = FITERR_PLUS(ipar,iter)
            EMINUS             = ABS ( FITERR_MINUS(ipar,iter) )
            ERRTYPE(ipar)      = ERRTYPE_BAD
         endif

         FITERR_RATIO(ipar,iter)   = EPLUS / EMINUS
         FITERR(ipar,iter)         = 0.5 * ( EPLUS + EMINUS )

         FITVAL_STORE(ipar)    = FITVAL(ipar,iter)
         FITERR_STORE(ipar)    = FITERR(ipar,iter)
         INIVAL_STORE(ipar)    = INIVAL(ipar)
         ERRTYPE_STORE(ipar)   = ERRTYPE(ipar)

c store FITVCAL in 'LC' array (might get over-written later by PDFVAL

         LCVAL_STORE(ipar) = FITVAL_STORE(ipar)
         LCERR_STORE(ipar) = MIN(99.9,FITERR_STORE(ipar))

c print results for floated parameters only

         if ( FLOATPAR(ipar)
     &     .or. NFIXPAR .EQ. NFITPAR_MN
     &     .or .IPAR    .EQ. 1             ! IPAR_ITER - Nov 2014
     &           ) then
            CALL PRINT_FITPAR(SNLC_CCID, iter, ipar, 'fit' )
         endif

c do stuff on last iteration
         IF ( iter .EQ. NFIT_ITERATION .and. FLOATPAR(ipar) ) then
            etmp = ERRTYPE(ipar)
            NERRTYPE(etmp) = NERRTYPE(etmp) + 1

            if ( iter > 1 ) then
              ERR_FINAL = FITERR(ipar,iter)
              ERR_LAST  = FITERR(ipar,iter-1)
              ERR_AVG   = 0.5*(ERR_FINAL+ERR_LAST)
              if ( ERR_AVG > 1.0E-12 ) then
                LCFRACERRDIF_STORE(ipar) = (ERR_FINAL-ERR_LAST)/ERR_AVG
              endif
            endif
         ENDIF

444   CONTINUE   ! end loop over IPAR

c ----------------------
c 9/29/2007: get error matrix

      IF ( LREPEAT_MINOS ) MNSTAT_COV = MNSTAT_COV + 10
      CALL MNEMAT(FITERRMAT_SPARSE,MXFITPAR)

c compute correlation matrix from error matrix

      J = 0
      DO ipar = 1, NFITPAR_MN
        if ( FLOATPAR(ipar) ) then
           j = j + 1
           JPAR(ipar) = j
        endif
      ENDDO

      DO ipar1 = 1, NFITPAR_MN
      DO ipar2 = 1, NFITPAR_MN

         FITERRMAT(ipar1,ipar2) = 0.0
         FITCORMAT(ipar1,ipar2) = 0.0

         FLOATBOTH = ( FLOATPAR(ipar1) .and. FLOATPAR(ipar2) )
         if ( FLOATBOTH ) then
           J1 = JPAR(ipar1)
           J2 = JPAR(ipar2)
           EMAT8     = FITERRMAT_SPARSE(J1,J2)
           SQERR8(1) = FITERRMAT_SPARSE(J1,J1)
           SQERR8(2) = FITERRMAT_SPARSE(J2,J2)

           IF  ( SQERR8(1) > 0.0 .and. SQERR8(2) > 0.0 ) then
             ERR8(1) = sqrt ( SQERR8(1) )
             ERR8(2) = sqrt ( SQERR8(2) )
             FITCORMAT(ipar1,ipar2) = EMAT8/(ERR8(1) * ERR8(2) )
             FITERRMAT(ipar1,ipar2) = EMAT8
           else
           endif

         endif
      ENDDO
      ENDDO

      RETURN
      END   ! end MNFIT_STOREPAR

C ======================================
CDECK  ID>,  ERRTYPE_STR. 
      FUNCTION ERRTYPE_STR(ERRTYPE)
      IMPLICIT NONE

      INTEGER ERRTYPE  ! (I) error type

      CHARACTER ERRTYPE_STR*1


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C --------------- BEGIN -------------

      if ( ERRTYPE .EQ. ERRTYPE_MINOS ) then
        ERRTYPE_STR = 'M'
      else if ( ERRTYPE .EQ. ERRTYPE_PARAB ) then
        ERRTYPE_STR = 'P'
      else if ( ERRTYPE .EQ. ERRTYPE_MARG ) then
        ERRTYPE_STR = 'm'
      else if ( ERRTYPE .EQ. ERRTYPE_BAD ) then
        ERRTYPE_STR = '?'
      else if ( ERRTYPE .EQ. 0 ) then
        ERRTYPE_STR = ' '
      else
        ERRTYPE_STR = '?'
      endif

      RETURN
      END

C =======================================
CDECK  ID>,  PRINT_FITPAR. 
      SUBROUTINE PRINT_FITPAR(CCID, iter, ipar, type )
c
c standard print-line for fit-result or pdf-result.
c
c type = 'fit' : uses current FITVAL and FITERR
c type = 'pdf' : uses current PDFVAL and PDFERR
c
c Note that ITER is used only for 'fit' option
c
c Jun 2013: return if we are no longer in VERBOSE mode and iter < NFIT_ITER
c            (to reduce output for BIG jobs)
c
      IMPLICIT NONE

c subroutine args

      INTEGER  ITER, IPAR  ! (I) SN cand id and IPAR to print
      CHARACTER
     &    CCID*(*)   ! (I) char string cand id
     &   ,type*(*)   ! (I) 'fit' or 'pdf' type of result


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER LL
      REAL*8  VAL, ERR
      LOGICAL LQUIET
      CHARACTER STRING_VAL*12

c function
      CHARACTER ERRTYPE_STR*1

C --------------- BEGIN -------------

      LQUIET = .NOT. STDOUT_UPDATE

      IF ( LQUIET ) RETURN

      IF ( type .EQ. 'fit' ) then
        VAL = FITVAL(ipar,iter)
        ERR = FITERR(ipar,iter)
      ELSE IF ( type .EQ. 'pdf' ) then
        VAL = PDFVAL(ipar)
        ERR = PDFERR(ipar)
      ELSE

      ENDIF

c write par value into string using format
      WRITE(STRING_VAL,211) VAL
211   FORMAT(G11.5)
      IF ( VAL > 1.0E4 ) THEN  ! this is PEAKMJD
        WRITE(STRING_VAL,212) VAL
212     FORMAT(F11.3)
      ENDIF

      LL = INDEX(CCID,' ') - 1
      IF ( LL .LE. 0 ) LL = MXCHAR_CCID
      WRITE (6,430)  CCID(1:LL), type, IPAR
     &    , PARNAME_STORE(IPAR), STRING_VAL, ERR
     &    , ERRTYPE_STR ( ERRTYPE(IPAR) )

 430    FORMAT (T8,'CID ',A,2x, A,'par(', I2, '):',A14,' = ',
     &                 A11,' +/- ', G10.4, '(',A,')' )

      CALL FLUSH(6)

      RETURN
      END    ! end of PRINT_FITPAR

C ==============================
CDECK  ID>,  BOOK_CONTOUR. 
      SUBROUTINE BOOK_CONTOUR ( h1,h2, Npt, IPAR1, IPAR2 )
c
c Store information about this contour.
c The contour is made with MNCONT after
c the fit has finished.
c
c The contour results are booked in h1,h2
c when the user calls PLOT_CONTOUR.
c
c ----------------------------------

      IMPLICIT NONE

      INTEGER
     &    h1,h2   ! (I) hbook ids for storage (in PLOT_CONTOUR)
     &   ,NPT     ! (I) Number of points for contour
     &   ,IPAR1   ! (I) 1st param index
     &   ,IPAR2   ! (I) 1st param index

c local var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNCONTCM. inserted below by ypatchy. 

      INTEGER  MXPLOT_CONT, MXBIN_CONT
      PARAMETER (
     &   MXPLOT_CONT  = 5    ! max number of contour plots per SN
     &  ,MXBIN_CONT   = 100  ! max number of contour bins
     &     )

c define arrays to hold MNCONT informatino for contour plots

      INTEGER
     &   NPLOT_CONT                 ! number of user-contour plots
     &  ,HID_CONT(2,MXPLOT_CONT)    ! store hbook ids for vectors
     &  ,IPAR_CONT(2,MXPLOT_CONT)   ! stores which IPAR for contours
     &  ,NPT_CONT(MXPLOT_CONT)      ! stores Npt per contour plot
     &  ,NPT_FOUND(MXPLOT_CONT)

      REAL*8
     &   VCONT8(MXBIN_CONT,2,MXPLOT_CONT)  ! vector array for IPAR1

      COMMON / CONTOURCOM4 / NPLOT_CONT
     &   ,HID_CONT, IPAR_CONT, NPT_CONT, NPT_FOUND

      COMMON / CONTOURCOM8 /  VCONT8



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      INTEGER N, L1, L2

C ------------- BEGIN -------------

      NPLOT_CONT = NPLOT_CONT + 1
      N = NPLOT_CONT

      NPT_CONT(N)   = NPT
      HID_CONT(1,N) = h1
      HID_CONT(2,N) = h2

      IPAR_CONT(1,N) = ipar1
      IPAR_CONT(2,N) = ipar2

      L1 = INDEX ( PARNAME_STORE(ipar1), ' ') -1
      L2 = INDEX ( PARNAME_STORE(ipar2), ' ') -1

      write(6,20) PARNAME_STORE(ipar1)(1:L1),
     &            PARNAME_STORE(ipar2)(1:L2), NPT

20    format(T5,'BOOK_CONTOUR for ',A,' vs. ', A,
     &    ' with ',I3,' points. ' )

      RETURN
      END


C ======================================
CDECK  ID>,  PDF_INIT. 
      SUBROUTINE PDF_INIT()
c
c Created Nov 24, 2009 by R.Kessler
c
c Init PDFXXX arrays before marginalizing or before running
c the MCMC option.  The main issue here is to make sure that
c fixed parameters (like ITER) get transfered to
c the PDFVAL array.
c
c ---------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c local var
      INTEGER IPAR, IPAR2

C --------------- BEGIN -----------------

      DO 40 ipar = 1, NFITPAR_MN
         PDFVAL(ipar) = FITVAL(ipar,NFIT_ITERATION)

c reset PDF-marginalized values for floated parameters
         IF ( FLOATPAR(ipar) ) then
            PDFERR(ipar)  = -9.0
            PDFVAL(ipar)  = -9.0
         ENDIF

c zero the covariance matrix

         DO ipar2 = 1, NFITPAR_MN
           PDFERRMAT(ipar,ipar2) = 0.0
           PDFCORMAT(ipar,ipar2) = 0.0
         ENDDO
40    CONTINUE

      RETURN
      END
C ======================================
CDECK  ID>,  PDF_STORE. 
      SUBROUTINE PDF_STORE()
c
c Created Nov 11, 2009 by R.Kessler
c
c Utility to store marginalized/MCMC PDF values,
c and re-compute chi2 and fit-probs.
c [Code moved from end of MARG_DRIVER]
c
c Nov 17, 2011: replace CERNLIB's PROB() with PROB_CHI2NDOF
c
c -----------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c local var

      INTEGER IPAR, NDOF, i

      DOUBLE PRECISION
     &    GRAD8(MXFITPAR)
     &   ,CHI8, USRFUN

      REAL  PCHI2
      EXTERNAL USRFUN

c function
      REAL*8 PROB_CHI2NDOF

C ----------------- BEGIN -----------

c print/store results

      DO 30 ipar = 1, NFITPAR_MN

         PDFVAL_STORE(ipar)   = PDFVAL(ipar)
         PDFERR_STORE(ipar)   = PDFERR(ipar)
         PDFPROB2_STORE(ipar) = PDFPROB2(ipar)

c over-write LCVAL[ERR] array with pdf-avarges

         LCVAL_STORE(ipar) = PDFVAL_STORE(ipar)
         LCERR_STORE(ipar) = MIN(99.9,PDFERR_STORE(ipar))

         if ( .NOT. FLOATPAR(ipar)  ) goto 30

         CALL PRINT_FITPAR( SNLC_CCID, 0, ipar, 'pdf' )
         CALL FLUSH(6)

30    CONTINUE

c ----------------------------------------------------
c re-compute chi2, prior-chi2 and prob with marginalized values.

c start with PRIOR-only chi2.
      CALL FCNSNLC(NFITPAR_MN, GRAD8, CHI8, PDFVAL,
     &       FCNFLAG_PRIOR_ONLY, USRFUN)
      LCCHI2_STORE(3) = CHI8

c now get contribution from ln(sigma)-terms

      CALL FCNSNLC(NFITPAR_MN, GRAD8, CHI8, PDFVAL,
     &       FCNFLAG_SIGMA_ONLY, USRFUN)
      LCCHI2_STORE(4) = CHI8

c Now get full chi2 ...

      CALL FCNSNLC(NFITPAR_MN, GRAD8, CHI8, PDFVAL,
     &      FCNFLAG_LAST, USRFUN)
      LCCHI2_STORE(1) = CHI8

c data-only chi2 if full-prior chi2.
      LCCHI2_STORE(2) = CHI8 - LCCHI2_STORE(3)

c compute fit-probs.

      DO i     = 1, 4
        chi8   = LCCHI2_STORE(i)
        NDOF   = NDOF_STORE(i)

        if ( NDOF .GT. 0 .and. CHI8 .GT. 0.0 ) then
           PCHI2  = SNGL( PROB_CHI2NDOF(CHI8,NDOF) )
        else
           PCHI2 = 1.0
        endif

        LCPROBCHI2_STORE(i) = PCHI2
      ENDDO

      CALL FLUSH(6)

      RETURN
      END


C =============================================
CDECK  ID>,  RDMCMCNML. 
      SUBROUTINE RDMCMCNML(IERR)
      IMPLICIT NONE
c
c Created Nov 11, 2009 by R.Kessler
c Read optional &MCMCINP namelist.
c If &MCMCINP is not in the namelist file,
c just exit quietly. If MCMCNML is there,
c read it and print a few comments
c
c --------------------------


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,MCMCCOM. inserted below by ypatchy. 

c Created Nov 2009 for Ben Dilday's  MCMC method

c a bunch of MCMC stuff
      LOGICAL LMCMC
     &  ,LTUP_MCMC    ! book/fill special ntuple

      INTEGER
     &   NMCMC_EVAL        ! number of total evaluations for MCMC
     &  ,IMCMC_FLAG        ! a generic flag for MCMC variations
     &  ,NMCMC_CHAINS      ! number of chains to run
     &  ,NMCMC_BURN        ! size of burn in
     &  ,IMCMC_STORE       ! store every nth chi2 in the ntuple

      CHARACTER
     &  CHOPT_MCMC*16     ! ??

      REAL
     &   MCMC_NSIG_STEP   ! ??
     &  ,NSIG_MCMC_START  ! ??

      COMMON / SNFMCMC / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN,MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START

      NAMELIST / MCMCINP / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN, MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START


C =============================================

C +CDE,MCMCTUP. inserted below by ypatchy. 
c MCMCTUP parameters (created Nov 2009 by B.Dilday)

      INTEGER
     &   MXNTVAR
     &  ,MAX_NMCMC_TOT
     &  ,NTID
     &  ,NCALL_MCMCTUP

      PARAMETER (
     &     MXNTVAR = 100
     &   , MAX_NMCMC_TOT = 2000000 ! max entries for mcmc ntuple
     &   , NTID = IDTABLE_MCMC
     &     )

c     common block for ntuple stuff
      CHARACTER MCMCTUPNAMES(MXNTVAR)*8
      REAL MCMCTUPVALS(MXNTVAR)

      COMMON / MCMCTUPCOM / MCMCTUPNAMES
     &     ,MCMCTUPVALS, NCALL_MCMCTUP

c ----------------------------

      INTEGER IERR   ! 0=>OK,  else error

c local ars

      integer LL, iocheck, ISEED

      EXTERNAL RANDOMINIT

C -------------- BEGIN -----------
      IERR = 0

c ----------------------------------------
c set namelist defaults

      NMCMC_EVAL      = 10000
      IMCMC_FLAG      = -1
      NMCMC_CHAINS    = 1
      NMCMC_BURN      = 1000
      MCMC_NSIG_STEP  = 0.5
      CHOPT_MCMC      = ''
      LMCMC           = .FALSE.
      LTUP_MCMC       = .FALSE.
      IMCMC_STORE     = 1
      NSIG_MCMC_START = 3.0

c misc. init
      NCALL_MCMCTUP = 0
c --------------------------------

      LL = INDEX(nmlfile,' ' ) - 1

      OPEN (
     &    UNIT   = LUNNML
     &   ,file   = nmlfile
     &   ,status = 'OLD'
     &   ,ERR    = 900
     &       )

c try reading MCMCINP; if not there, just return quietly.
c Danger here is that a namelist bug is not distinguished
c from a missing namelist.

      READ ( LUNNML, NML = MCMCINP, ERR = 900, IOSTAT = iocheck )
      CLOSE ( UNIT = LUNNML )

      if ( iocheck .NE. 0 ) return

      CALL PRBANNER ( " FOUND and READ MCMCINP NAMELIST. " )


      WRITE ( 6 , NML = MCMCINP )

c check for namelist over-rides from command line.

      CALL MCMCINP_OVERRIDE(IERR)
        IF ( IERR .NE. 0 ) RETURN


      IF ( LMCMC ) THEN
        ISEED = 12345
      ENDIF

C #################################################

         GOTO 999

C #################################################

900   CONTINUE
      C1err = 'Could not read  &MCMCINP namelist '
      C2err = 'Check ' // nmlfile
      CALL  MADABORT("RDMCMCNML", C1ERR, C2ERR)

999   CONTINUE
      RETURN
      END  ! end of RDMCMCNML


C =============================================
CDECK  ID>,  MCMC_DRIVER. 
      SUBROUTINE MCMC_DRIVER(HOFF_MARG
     &     , NMCMC_CHAINS
     &     , NMCMC_EVAL
     &     , NMCMC_BURN
     &     , LTUP_MCMC
     &     , IMCMC_STORE
     &     , MCMC_NSIG_STEP
     &     , NSIG_MCMC_START
     &     )
c
c Created Nov 2009 by B. Dilday;
c installed in snana Nov 2009 by R.Kessler
c Markov Chain Monte Carlo driver
c
c
c Oct 1 2012 RK replace HBOOK1 and HFILL with LCPLOT utility
c
c Feb 10, 2012 RK - comment out call to MCMCTUP until it replaces
c                   CERNLIB calls with SNTABLE_xxx functions
c
c -------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,MCMCTUP. inserted below by ypatchy. 
c MCMCTUP parameters (created Nov 2009 by B.Dilday)

      INTEGER
     &   MXNTVAR
     &  ,MAX_NMCMC_TOT
     &  ,NTID
     &  ,NCALL_MCMCTUP

      PARAMETER (
     &     MXNTVAR = 100
     &   , MAX_NMCMC_TOT = 2000000 ! max entries for mcmc ntuple
     &   , NTID = IDTABLE_MCMC
     &     )

c     common block for ntuple stuff
      CHARACTER MCMCTUPNAMES(MXNTVAR)*8
      REAL MCMCTUPVALS(MXNTVAR)

      COMMON / MCMCTUPCOM / MCMCTUPNAMES
     &     ,MCMCTUPVALS, NCALL_MCMCTUP

c ----------------------------

c declare subroutine args

      INTEGER HOFF_MARG    ! (I) hbook offset
      INTEGER NMCMC_CHAINS ! (I) number of chains to run (per SN)
      INTEGER NMCMC_EVAL   ! (I) number of evaluations (per chain, per SN)
      INTEGER NMCMC_BURN   ! (I) size of burn in
      LOGICAL LTUP_MCMC    ! (I) store mcmc in a ntuple?
      INTEGER IMCMC_STORE  ! (I) if ltup_mcmc set, store only every IMCMC_STORE values
      REAL MCMC_NSIG_STEP  ! (I)
      REAL NSIG_MCMC_START ! (I) perturb MCMC starting point from minuit max-likelihood value

c local variables
      INTEGER iv
     &     ,cid
     &     ,idum
     &     ,imcmc
     &     ,IFLAG
     &     ,NVAR
     &     ,IPAR
     &     ,JPAR
     &     ,oset
     &     ,ichain
     &     ,jmcmc
     &     ,NMCMC_TOT
     &     ,NMCMC_TOT_EVALS
     &     ,IERR
     &     ,nvtot
     &     ,hid
     &     ,nbin
     &     ,LL

      CHARACTER sdir*20
     &     , subdirname*40
     &     , topdir*20
     &     ,chis*80

      LOGICAL LDMP / .FALSE. /

      REAL  XNTUP(MXNTVAR)
     &     ,MCMC_STORE(MXFITPAR, MAX_NMCMC_TOT)

      REAL pchi2 , dum4, wgt
     &     ,xmin(MXFITPAR), xmax(MXFITPAR)

      REAL*8 CHI2
     &     , XVAL(MXFITPAR)     ! fit parameters
     &     , SVAL(MXFITPAR)     ! fit parameter errors
     &     , MVAL(MXFITPAR)     ! fit parameters
     &     , GRAD8(MXFITPAR)
c     &     ,PDFSUM_GRID(MXGRID,MXFITPAR) ! PDF vs. par to plot 1-d pdf
     &     ,MCMC_DENOM8
     &     ,CUR_DENOM8
     &     ,SQERR

      REAL*8
     &      MCMC_SUM(MXFITPAR)
     &     ,MCMC_SUM2(MXFITPAR, MXFITPAR)
     &     ,MCMC_MEAN(MXFITPAR)
     &     ,MCMC_SIGMA(MXFITPAR)

c functions
      REAL*8 PROB
      DOUBLE PRECISION USRFUN, GETRAN_GAUSS

      INTEGER  MCMCFUN
      EXTERNAL USRFUN

C ------------------- BEGIN ---------------------

      print*, ' '
      print*,'  MCMC_DRIVER called for CID=', SNLC_CCID
      CALL FLUSH(6)

      NMCMC_TOT = NMCMC_EVAL*NMCMC_CHAINS
      NMCMC_TOT_EVALS = NMCMC_TOT*N_SNLC_PROC

c init PDFVAL = FITVAL so that fixed params get transfered.
      CALL PDF_INIT()

c there seems to be a limit for number of values that can be
c stored in an ntuple; abort right away if LTUP is set,
c and NMCMC_TOT_EVALS is larger than this
c the limit may be system dependent??

      IF ( NMCMC_TOT_EVALS/IMCMC_STORE .GT. MAX_NMCMC_TOT .AND.
     &     LTUP_MCMC ) THEN
         c1err = "NMCMC_TOT_EVALS is too big!"
         write(c2err,660) NMCMC_TOT, MAX_NMCMC_TOT
660      format('NMCMC_TOT=',I10,' exceed limit of ', I8 )
         CALL MADABORT( "MCMC_DRIVER", c1err, c2err )
      ENDIF

c book ntuple here

      IF ( LTUP_MCMC ) THEN
cc         CALL MCMCTUP(0, MCMCNTUPN)
      ENDIF

c compute denominator for computing mean, sigma and do a
c sanity check on length of burn-in

      if ( NMCMC_BURN .GE. NMCMC_EVAL ) THEN
         c1err = "NMCMC_BURN cannot be greater than NMCMC_EVAL!"
         c2err = " "
         CALL MADABORT( "MCMC_DRIVER", c1err, c2err )
      ELSE
         MCMC_DENOM8 = DBLE((NMCMC_EVAL-NMCMC_BURN)*NMCMC_CHAINS)
         wgt = 1.0/MCMC_DENOM8
      ENDIF

      iflag = FCNFLAG_USER
c      iflag = 4
      nvar = NFITPAR_MN

      IF ( LDMP ) THEN
        print*,'nmcmc= ', nmcmc_eval
        print*,'nvar= ', nvar
      ENDIF

      inival(1) = 1
      inival(9) = 0.05

      DO 51 ipar = 1, nvar
         xval(ipar) = FITVAL_STORE(ipar)
         sval(ipar) = FITERR_STORE(ipar)
         mval(ipar) = xval(ipar)
c         xval(ipar) = xval(ipar)
c     &     + sval(ipar)*NSIG_MCMC_START*GETRAN_GAUSS()
 51   CONTINUE

      call fcnsnlc(nvar, grad8, chi2, xval, iflag, usrfun)

      IF ( LDMP ) THEN
        print*,'fcnsnlc= ', chi2
        print*,'iflag= ',iflag
c      idum = testy(nvar, grad8, chi2, xval, sval, iflag, usrfun)
        print*,'idum fortran= ', idum
      ENDIF

c     initialize sumations to 0
c     initialize xmin and xmax
      DO ipar = 1, nvar
         xmin(ipar) =  9E9
         xmax(ipar) = -9E9
         MCMC_SUM(ipar) = 0.0
         DO jpar = 1, nvar
            MCMC_SUM2(ipar, jpar) = 0.0
         ENDDO
      ENDDO

      CUR_DENOM8 = 0.0

c loop over number of chains
      do ichain = 1, NMCMC_CHAINS
         oset = (ichain-1)*nmcmc_eval

c     choose a new starting point
         DO 52 ipar = 1, nvar

            if ( .not. FLOATPAR(ipar) ) goto 52
            xval(ipar) = FITVAL_STORE(ipar)
            sval(ipar) = FITERR_STORE(ipar)
            xval(ipar) = xval(ipar) +
     &         sval(ipar)*NSIG_MCMC_START*GETRAN_GAUSS(1)
c     initialize the chi**2 for passing to snfit_mcmc_
            call fcnsnlc(nvar, grad8, chi2, xval, iflag, usrfun)
 52      CONTINUE

c     loop over number of evaluations per chain
         do jmcmc = 1, nmcmc_eval
            imcmc = oset + jmcmc

               idum = mcmcfun(nvar, chi2,
     &              mval, xval, sval, iflag
     &              , usrfun
     &              )

       IF ( LDMP ) THEN
c       IF ( LDMP .or. .not. LDMP ) THEN
          DO jpar = 1, nvar
             print*,'ipar= ', jpar, ' val= ', xval(jpar)
             CALL FLUSH(6)
          ENDDO
       ENDIF
c     now values have been returned
c     if we are not still in burn-in phase, then add to the mean and sigma sumations, fill pdf histograms...
               IF ( jmcmc .GT. NMCMC_BURN ) THEN
                  CUR_DENOM8 = CUR_DENOM8 + 1
                  DO ipar = 1, nvar
                     IF ( FLOATPAR(ipar) ) THEN

                        dum4 = sngl(xval(ipar)-mval(ipar))

                        IF ( dum4 .GT. xmax(ipar) ) THEN
                           xmax(ipar) = dum4
                        ENDIF

                        IF ( dum4 .LT. xmin(ipar) ) THEN
                           xmin(ipar) = dum4
                        ENDIF

c     fill after fit is done, so that we know the min, max
c     hid = HOFF_MARG + ipar
c     CALL HFILL(hid, dum4, 0.0, wgt)

                        MCMC_STORE(ipar, int(CUR_DENOM8)) = xval(ipar)

                        MCMC_SUM(ipar)  = MCMC_SUM(ipar)  + xval(ipar)

                        DO jpar = 1, nvar
                           IF ( FLOATPAR(jpar) ) THEN
                              MCMC_SUM2(ipar, jpar) =
     &                             MCMC_SUM2(ipar, jpar)
     &                             + xval(ipar)*xval(jpar)

                           ENDIF ! jpar is floated
                        ENDDO   ! jpar
                     ENDIF      ! ipar is floated
                  ENDDO         ! ipar
               ENDIF            ! jmcmc<nburn

c     check if we should fill the ntuple
               if ( LTUP_MCMC .AND. mod(imcmc, IMCMC_STORE)==0) THEN
c     need to fill the ntuple value array before calling MCMCTUP
                  iv = 0
                  DO ipar = 1, mxfitpar
                     if ( FLOATPAR(ipar) ) THEN
                        iv = iv + 1
                        mcmctupvals(iv) = xval(ipar)
                     ENDIF
                  ENDDO
c     we need the chi2 value
                  iv = iv + 1
                  mcmctupvals(iv) = chi2

c     number of degrees of freedom
                  iv = iv + 1
                  mcmctupvals(iv) = NDOF_STORE(2)

c     mcmc index
                  iv = iv + 1
                  mcmctupvals(iv) = float(imcmc)

c     was the new point accepted?
                  iv = iv + 1
                  mcmctupvals(iv) = float(idum)

c     done

cc                  IF ( LTUP_MCMC ) CALL MCMCTUP(1, MCMCNTUPN)
               ENDIF

               if ( mod(imcmc, 2000) .EQ. 0 ) then
                  print*, '     imcmc= ', imcmc, ' / ', nmcmc_tot
                  call flush(6)
               endif
            enddo               ! loop over evaluations
         enddo                  ! loop over chains

c     now compute mean, sigma, fill marg arrays, etc...
         IERR = 0

c     mean of distribution for each floated par
         DO ipar = 1, nvar
            if ( FLOATPAR(ipar) ) THEN
               MCMC_MEAN(ipar) = MCMC_SUM(ipar)/MCMC_DENOM8
               PDFVAL(ipar) = MCMC_MEAN(ipar)
            ENDIF
         ENDDO

c     elements of covariance matrix
         DO ipar = 1, nvar
         if ( FLOATPAR(ipar) ) THEN
            DO jpar = 1, nvar
               if ( FLOATPAR(jpar) ) THEN
                  SQERR = MCMC_SUM2(ipar,jpar)/MCMC_DENOM8
     &                 -MCMC_MEAN(ipar)*MCMC_MEAN(jpar)
                  PDFERRMAT(ipar, jpar) = sngl(SQERR)
               ENDIF
            ENDDO
         ENDIF
      ENDDO

c     check that diagonal elements are >0
      DO ipar = 1, nvar
         SQERR = PDFERRMAT(ipar, ipar)
         IF ( SQERR .GE. 0.0 ) THEN
            MCMC_SIGMA(ipar) = SQRT(SQERR)
            PDFERR(ipar) = MCMC_SIGMA(ipar)
         ELSE
            write(c1err,666) PARNAME_STORE(IPAR), SQERR, SNLC_CCID
 666        format('SQERR(', A, ') = ', G12.4,'  for CID=',A )
            IERR = -1
            MCMC_SIGMA(ipar) = -SQRT(ABS(SQERR))
         ENDIF
      ENDDO

      DO ipar = 1, nvar
         if ( FLOATPAR(ipar) ) THEN
            DO jpar = 1, nvar
               if ( FLOATPAR(jpar) ) THEN
                  SQERR = MCMC_SUM2(ipar,jpar)/MCMC_DENOM8
     &                 -MCMC_MEAN(ipar)*MCMC_MEAN(jpar)
                  PDFERRMAT(ipar, jpar) = SQERR
                  PDFCORMAT(ipar, jpar) = PDFERRMAT(ipar, jpar)/
     &                 (PDFERR(ipar)*PDFERR(jpar))
               ENDIF
            ENDDO
         ENDIF
      ENDDO

c     ---------------------------
c     book 1d pdfs here
      nbin = 41
      IF ( HOFF_MARG .GT. 0 ) THEN
         DO ipar = 1, nvar
            if ( FLOATPAR(ipar) ) THEN
               hid = HOFF_MARG + ipar
               LL = index ( PARNAME_STORE(ipar), ' ' ) - 1
               write(chis,21)
     &              PARNAME_STORE(IPAR)(1:LL)
     &              , PARNAME_STORE(IPAR)(1:LL)
     &              , SNLC_CCID

 21            format(' margin. PDF(',A,'-',A,'?fit!) for CID=',A6)
            ENDIF
         ENDDO
      ENDIF

c     store results and print to screen
      CALL PDF_STORE()

      IF ( IERR .LT. 0 ) THEN
         c2err = 'Check MCMC error calc.'
         CALL MADABORT( "MCMC_DRIVER", c1err, c2err )
      ENDIF

      RETURN
      END
C =============================================
CDECK  ID>,  MCMCFUN. 
      INTEGER FUNCTION MCMCFUN(nvar, chi2,
     &     mval, xval, sval, iflag, usrfun)

c Created Nov 2009 by B.Dilday
c
c
c
c This function constitutes one step of the MCMC algorithm.
c The current parameters and the associated chi**2 value are
c passed in 'xval' and 'chi2'.  A new set of parameters is
c generated from a proposal distribution,  and accepted
c with probability equal to the the ratio of the probabilities
c associated with each chi**2 value.  The proposal distribution
c is a gaussian with a diagonal covariance  matrix and with a
c step size in each dimension proportional to the estimated
c error (e.g., from minuit minimization) on the parameter
c (passed in 'sval'). the proportionality constant is given
c by the global variable 'MCMC_NSIG_STEP'. The proposal
c distribution is independent of the current values of the
c parameters.  If the proposed point is accepted, then the
c values are returned in 'xval' and the function returns 1
c (0 otherwise).
c Possible improvements:
c - use a non-diagonal covariance matrix
c
c
c Jan 2013 RK - replace CERNLIB random generator with
c               sntools random generators: snran1 & gaussran().
c               WARNING - not tested !!!
c -----------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,MCMCCOM. inserted below by ypatchy. 

c Created Nov 2009 for Ben Dilday's  MCMC method

c a bunch of MCMC stuff
      LOGICAL LMCMC
     &  ,LTUP_MCMC    ! book/fill special ntuple

      INTEGER
     &   NMCMC_EVAL        ! number of total evaluations for MCMC
     &  ,IMCMC_FLAG        ! a generic flag for MCMC variations
     &  ,NMCMC_CHAINS      ! number of chains to run
     &  ,NMCMC_BURN        ! size of burn in
     &  ,IMCMC_STORE       ! store every nth chi2 in the ntuple

      CHARACTER
     &  CHOPT_MCMC*16     ! ??

      REAL
     &   MCMC_NSIG_STEP   ! ??
     &  ,NSIG_MCMC_START  ! ??

      COMMON / SNFMCMC / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN,MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START

      NAMELIST / MCMCINP / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN, MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START


C =============================================

c declare function args

      INTEGER nvar ! (I) number of variables
      REAL*8 CHI2  ! (I/O) chi**2 value
      REAL*8 XVAL(MXFITPAR) ! (I/O) parameter values
      REAL*8 SVAL(MXFITPAR) ! (I) parameter errors
      REAL*8 MVAL(MXFITPAR) ! (I) parameter starting value
      INTEGER IFLAG         ! (I) input option
      DOUBLE PRECISION USRFUN ! (I) optional user function

c misc. args

      EXTERNAL USRFUN

      REAL*8 GRAD8(MXFITPAR)

      INTEGER IMNFLAG
     &     , ipar, itest, ilist

      REAL*8 XVAL_SV(MXFITPAR)
     &     , delchi2, sig
     &     , c1, c2, gval
     &     , rtest, rtest2
     &     , nsig8, prob8

c randon generators in sntools.c (RK - Jan 2013)
      REAL*8  GETRAN_FLAT1, GETRAN_GAUSS

C ===========================================
C ------------------- BEGIN -----------------
C ===========================================
      IMNFLAG = 90
      nsig8 = MCMC_NSIG_STEP

      c1 = chi2

      DO ipar = 1, NVAR
         XVAL_SV(ipar) = XVAL(ipar)
      ENDDO

      ILIST = 1
      DO ipar = 1, NVAR
         sig = SVAL(ipar)
c         IF ( sig .GT. 1E-9 ) THEN
c heres a better way to see if the variable is floated...
         IF ( FLOATPAR(ipar) ) THEN
            gval = GETRAN_GAUSS(ILIST)
            XVAL(ipar) = XVAL(ipar) + gval*sig*nsig8
         ENDIF
      ENDDO

      CALL FCNSNLC(nvar, grad8, chi2, xval, imnflag, usrfun)
      c2 = chi2
      delchi2 = c2-c1
      prob8 = DEXP(-0.5*delchi2)

      rtest = GETRAN_FLAT1();   ! RK - Jan 2013
      rtest2 = -2.0*DLOG(rtest)

      itest = 0
      IF ( rtest2 .GT. delchi2 ) THEN
         itest = 1
      ENDIF

      IF ( itest .GT. 0 ) THEN
         chi2 = c2
         c1 = c2
      ELSE
         DO ipar = 1, NVAR
            XVAL(ipar) = XVAL_SV(ipar)
         ENDDO
         chi2 = c1
      ENDIF

      MCMCFUN = itest
      RETURN
      END

C =======================================
CDECK  ID>,  MARG_DRIVER. 
      SUBROUTINE MARG_DRIVER( HOFF_MARG, OPT,
     &           MAX_INTEGPDF, NGRID_FINAL, NSIGMA)
c
c Created Aug 3, 2006 by R.Kessler
c
c Utility to compute pdf-averaged quantity for each fitpar.
c
c Call this routine AFTER fit is done ...
c this routine uses current FITVAL and FITERR,
c and fills PDFVAL(ipar) and PDFERR(ipar).
c
c Histograms book/filled:
c   HOFF:         PDF value for each FCNPDF function call
c   HOFF + ipar : 1-dim PDF distribution for each fitted ipar
c
c
c  May 5, 2007: fix dumb bug. Need to init PDVAL(ipar) = FITVAL(ipar)
c               before integration to make sure that fixed parameters
c               are set in PDFVAL
c
c Oct 16, 2009: call INTEGPDF twice. First time set NGRID=7 to get
c               better estimate of errors. Second time set
c               NGRID = NGRID_FINAL. Change should run faster
c               if there are fewer iterations needed with NGRID_FINAL.
c
c Nov 24, 2009: call PDF_INIT() to init PDFXXX arrays
c
c -------------------------------------------

      IMPLICIT NONE

c input args

      INTEGER
     &    HOFF_MARG      ! (I) fill plots with hbook offset = HOFF
     &   ,OPT            ! (I) options
     &   ,MAX_INTEGPDF   ! (I) max number of iterations
     &   ,NGRID_FINAL    ! (I) # bins for each integrated dimension

      REAL  NSIGMA     ! (I) integrate +_ NSIGMA for exact pdf.

c -------------
c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &   ipar, ipar2
     &  ,JTIME1, JTIME2, JDIFTIME
     &  ,NEVAL        ! number of function evaluations
     &  ,LL, NDOF
     &  ,i, IERR
     &  ,NGRID, HOFF, NHDIM, HID_PDF, NBPDF(2)

      character chis*80, copt*6

      REAL*8 XMIN(2), XMAX(2), TMP
      LOGICAL LSYMERR

c functions
      CHARACTER ERRTYPE_STR*1
      REAL*8  PROB

c FCN args

      DOUBLE PRECISION
     &    GRAD8(MXFITPAR)
     &   ,CHI8
     &   ,USRFUN

      EXTERNAL USRFUN

c ------------------ BEGIN ------------

c require at least a few bins ...

      if ( NGRID_FINAL .LE. 0 ) RETURN

c set chi2 value for FCN function to quit

      IF ( PDFMIN .GT. 0.0 .and.
     &        OPT .EQ. OPT_INTEGPDF_QUITCHI2 ) THEN
        FITCHI2_QUIT = -2.0*DLOG(PDFMIN) + FITCHI2_MIN
      ELSE
        FITCHI2_QUIT = 1.0E20
      ENDIF

      COPT = 'GRID'   ! only option so far

c -----------------

      write(6,19) SNLC_CCID, NSIGMA, copt
19    format(/,T5,'MARG_DRIVER(CID ',A6,'): ',
     &      'compute P.D.F(+- ',F3.1,' sigma)', 2x, 'method=',A)

      IF ( FITCHI2_QUIT .LT. 1.0E19 ) then
        print*,'   CPU-saver ON  => FCNSNLC quits when CHI2 > ',
     &         FITCHI2_QUIT
      ELSE
        print*,'   CPU-saver OFF => FCNSNLC always computes full CHI2.'
      ENDIF

      CALL FLUSH(6)

      USEPDF_MARG  = .TRUE.
      ISTAGE_SNANA = ISTAGE_TEST

c --------------------------------------
c book plots

c start with monitor plot for FCNPDF value for each function call

      IF ( HOFF_MARG .GT. 0 ) THEN
         HID_PDF = HOFF_MARG ; NHDIM   = 1
         NBPDF(1) = 202 ;  XMIN(1)  = -20.1 ; XMAX(1)  =  +0.1
         CHIS  = 'log10(PDF) for integration' // char(0)
         CALL SNHIST_INIT(NHDIM, HID_PDF, CHIS,
     &              NBPDF, XMIN, XMAX, LEN(CHIS) )
      ENDIF

c init PDFVAL = FITVAL so that fixed parameters get transfered.

      CALL PDF_INIT()

c ---------------------
c get exact pdf by integrating over other fit-parameters

      JTIME1 = TIME()

c First marginalize with just 7 grid-points per variable.

      OPT   = 1   ! 1st round estimate
      NGRID = 7
      HOFF  = 0   ! skip histograms
      CALL INTEGPDF( OPT, HOFF,
     &        MAX_INTEGPDF, NGRID, DBLE(NSIGMA), NEVAL, IERR )

c final marginalization; use previous PDF for grid size estimate

      OPT   = 2
      NGRID = NGRID_FINAL
      HOFF  = HOFF_MARG
      CALL INTEGPDF( OPT, HOFF,
     &        MAX_INTEGPDF, NGRID, DBLE(NSIGMA), NEVAL, IERR )

c compute integration time.

      JTIME2   = TIME()
      JDIFTIME = JTIME2 - JTIME1

      LL = INDEX(SNLC_CCID,' ') - 1
      write(6,80) NEVAL, JDIFTIME, SNLC_CCID(1:LL)
80    format(T5,'MARG_DRIVER: Finished ',I7,' function calls in ',
     &         I4,' seconds  (SN ', A,')'   )
      print*,' '

c keep track of integration times.

      NCALL_INTEGPDF     = NCALL_INTEGPDF + 1
      TIME_INTEGPDF      = JDIFTIME
      TIMESUM_INTEGPDF   = TIMESUM_INTEGPDF + JDIFTIME
      tmp                = DBLE(TIMESUM_INTEGPDF)/DBLE(NCALL_INTEGPDF)
      TIMEAVG_INTEGPDF   = INT(TMP+0.5)

      if ( mod(NCALL_INTEGPDF,5) .EQ. 0 ) then
         print*,' '
         print*,'   (AVERAGE INTEGPDF TIME: ',
     &              TIMEAVG_INTEGPDF,'  seconds)'
         print*,' '
      endif

c call utility to store PDF results
      CALL PDF_STORE()

      RETURN
      END   ! end of MARG_DRIVER


C =======================================
CDECK  ID>,  INTEGPDF. 
      SUBROUTINE INTEGPDF(OPT, HOFF,
     &           MAX_INTEGPDF, NGRID, NSIGMA, NEVAL, IERR )
c ---------------------
c  Retruns p.d.f(DLMAG) integratged over other parameters;
c  integration is from +-NSIGMA * FITERR over each
c  dimension with non-zero INISTP.
c
c  The calling routine must set FITVAL(IPAR_DLMAG) = DLMAG,
c  and also set INISTP(IPAR_DLMAG) = 0.0 so that FCNPDF
c  knows to ignore the DLMAG-dimension in the integration.
c
c  OPT=1 => first estimate with small NGRID
c  OPT=2 => final estimate with final NGRID
c
c
c histograms are booked / filled for
c
c  HOFF          : function value for each call
c  HOFF + ipar   : pdf for each floated "ipar"
c
c
c  Feb 24, 2007: major upgrade to iterate if problem
c                is detected. See LREDO logic.
c
c                PDFERR(ipar) is now the RMS of the pdf distribution.
c
c Apr 28, 2007:
c  on 2nd iteration when prob at edge is too high, make more robust
c  estimate of integration region. Previously, integ-region was extended
c  by three times the shift in PDFVAL. Now, a Gaussian profile is
c  assumed, and an effective SIGMA is computed based on prob(at edge)
c  and current PDFVAL(ipar).  The integration limmit is then
c  changed to PDFVAL + NSIGMA*SIGMA
c  This improvement should help when MINUIT returns an error that
c  is way too small, but is still not flagged by BADERR.
c
c May 3, 2007: accept MAX_INTEGPDF as argument
c
c Aug 20, 2008: change MXPAR from 8 to 10
c               (to accomodate IPAR_LUMIPAR2 in STRETCH2 model)
c
c Oct 16, 2009:
c      use OPT=1,2 to determine which NGRID-iteration
c      Compute covariance & correlations: PDFCORMAT(ipar1,ipar2)
c
c      Fill PDRPROB2(ipar)
c
c Jan 4, 2010: add IERR argument. For PDF=0 error, abort only
c              if OPT=2. This gives both NGRID values a chance
c              to  succeed.
c
c Oct 01, 2012: use LCPLOT utility instead of HBOOK1 and HPAK
c
c Feb 06, 2013: replace LCPLOT util with SNHIST
c
c Jun 10 2013: protect ABORT when LPDFZERO=T using user namelist
c              ABORT_ON_MARGPDF0
c
c -------------------------------------------------

      IMPLICIT NONE

c function aarguments

      INTEGER
     &   OPT      ! (I) option
     &  ,MAX_INTEGPDF  ! (I) max # times to integrate
     &  ,NGRID    ! (I) # grid-bins for each dimension
     &  ,HOFF     ! (I) hbook offset
     &  ,NEVAL    ! (O) number of function calls.
     &  ,IERR     ! (O) 0=>OK

      REAL*8  NSIGMA   ! (I) integrate +- NSIGMA in each dimension

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER MXPAR, MXGRID

      PARAMETER (
     &    MXPAR   = 10   ! max number of fit paramters/dimensions
     &   ,MXGRID  = 30
     &     )

      INTEGER
     &   IPAR, IPAR2
     &  ,NBINTOT
     &  ,IBIN
     &  ,IBIN_OFF
     &  ,IGRID
     &  ,NDIM, IDIM, IDIM2
     &  ,IPAR_DIM(MXPAR)  ! IPAR for each dimension to integrate
     &  ,IBIN_DIM(MXPAR)  ! local grid-bin for each dimension
     &  ,NN, i
     &  ,NPASS
     &  ,HID, NHDIM, LL, NUM
     &  ,ITER
     &  ,NPDF, IBIN_PLOT, NB(2)

      REAL*8
     &   PARVAL_MIN(MXPAR)
     &  ,PARVAL_MAX(MXPAR)
     &  ,PARVAL_BINSIZE(MXPAR)
     &  ,PARDIF_MIN(MXPAR)
     &  ,PARDIF_MAX(MXPAR)
     &  ,PARVAL(MXPAR)
     &  ,PARVAL_GRID(MXGRID,MXPAR)
     &  ,TMP, TMPVAL
     &  ,DVOL
     &  ,X8(MXPAR)
     &  ,PDF, XPDF(2), WGT
     &  ,PDFWSUMCOR(0:MXPAR,0:MXPAR)   ! wgted sum for correlations
     &  ,PDFSUMCOR
     &  ,PDFWSUM(0:MXPAR)          ! wgted sum for each ipar
     &  ,PDFSUM                    ! PDF sum for each ipar
     &  ,PDFSUM_GRID(MXGRID,MXPAR)  ! PDF vs. par to plot 1-d pdf
     &  ,PDFMAX(MXPAR)             ! max over grid for each ipar
     &  ,TMP_RANGE(2,MXPAR)
     &  ,PDF1D(MXGRID,MXPAR)
     &  ,SUM0, SUM1, SUM2, XN, XTMP
     &  ,SQERR, E12, E1xE2, PDFTMP
     &  ,PDF_NBR1, PDF_NBR2
     &  ,XMIN(2), XMAX(2), XVAL(2)


      LOGICAL
     &   LTMP
     &  ,LPDFZERO
     &  ,LREDO
     &  ,LREDO_ALL
     &  ,LDMP_DEBUG

      CHARACTER chis*80, choice*12

c function

      REAL*8   FCNPDF
      EXTERNAL FCNPDF

c ----------------- BEGIN ------------

      NEVAL    = 0  ! init output arg
      IERR     = 0

      NPASS    = 0

      ITER = NFIT_ITERATION

      DO ipar = 1, NFITPAR_MN
         PARVAL_MIN(ipar) = 0.0
         PARVAL_MAX(ipar) = 0.0
         PARDIF_MIN(ipar) = 0.0
         PARDIF_MAX(ipar) = 0.0
      ENDDO

      LDMP_DEBUG = .FALSE.

      NHDIM    = 1  ! 1D histo

C =====================================
2     CONTINUE
      NPASS = NPASS + 1

c init some useful things.

      DVOL      = 1.0
      NBINTOT   = 1
      NDIM      = 0  ! number of dimensions to integrate PDF
      PDFSUM    = 0.0
      PDFSUMCOR = 0.0
      LREDO_ALL = .FALSE.

C set up integration limits for each parameter

      DO 30 ipar = 1, NFITPAR_MN

         PDFWSUM(ipar) =  0.0
         PDFMAX(ipar)  =  0.0

         do ipar2 = 1, NFITPAR_MN
            PDFWSUMCOR(ipar,ipar2) = 0.0
         enddo

         do igrid = 1, NGRID
            PDFSUM_GRID(igrid,ipar) = 0.0
         enddo

         if ( .not. FLOATPAR(ipar)  ) goto 30 ! skip fixed params

         NBINTOT = NBINTOT * NGRID

c keep track of which parameters to integrate
c (i.e., to ignore fixed parameters)

         NDIM = NDIM + 1
         IPAR_DIM(NDIM) = IPAR
         TMP_RANGE(1,ipar) = PARVAL_MIN(ipar)
         TMP_RANGE(2,ipar) = PARVAL_MAX(ipar)

         CALL INTEGRANGE(IPAR,NGRID,NSIGMA,PDF1D(1,ipar),  ! inputs
     &          LREDO, TMP_RANGE(1,ipar) ) ! outputs are LREDO & RANGE(1:2)

c set global REDO flag if any parameter-range is adjusted.

         LREDO_ALL = LREDO_ALL .OR. LREDO

30    CONTINUE  ! end of IPAR loop

c --------------------------------------------
c check if integration should proceed.
c Allow no more than three tries ... give "BEWARE" warning
c after 3 tries.

      IF ( NPASS .GT. 1 ) THEN

        IF ( LREDO_ALL ) THEN
           LL = INDEX(SNLC_CCID,' ') - 1

           if ( NPASS .LE. MAX_INTEGPDF ) then
              print*,'  ==> Integrate ',SNLC_CCID(1:LL),
     &            ' again with NGRID=', NGRID
              CALL FLUSH(6)
           else if ( OPT .EQ. 1 ) then
              goto 800

           else if ( OPT .EQ. 2 ) then  ! warn on final NGRID only

              print*,'  ==> Store ',SNLC_CCID(1:LL),
     &          ' result, but BEWARE !!!'
              CALL FLUSH(6)
c              print*,'  ==> Cannot converge for ',SNLC_CCID(1:LL)
c              IERR = -9  ! Dec 16, 2011

              GOTO 800  ! skip integration
           endif

        ELSE
           GOTO 800  ! skip integration
        ENDIF
      ENDIF

        CALL FLUSH(6)

c ----
c if we get here, then adjust integration range

      DO 31 ipar = 1, NFITPAR_MN

        if ( .not. FLOATPAR(ipar)  ) goto 31 ! skip fixed params

        PARVAL_MIN(ipar) = TMP_RANGE(1,ipar)
        PARVAL_MAX(ipar) = TMP_RANGE(2,ipar)

        TMP = FITVAL(ipar,ITER)
        PARDIF_MIN(ipar) = PARVAL_MIN(ipar) - TMP
        PARDIF_MAX(ipar) = PARVAL_MAX(ipar) - TMP

        TMP = PARVAL_MAX(ipar) - PARVAL_MIN(ipar)
        PARVAL_BINSIZE(ipar) = TMP / float(NGRID)

c compute volume element (used in brute-force method)

        DVOL = DVOL *  PARVAL_BINSIZE(ipar)

31    CONTINUE


c Now do the integration

      LPDFZERO = .TRUE.

      DO 770 IBIN = 1, NBINTOT

c determine local grid-bin for each dimension to integrate;
c the load local PARVAL with value at each grid-point.

         ibin_off = 0
         do idim  = 1, NDIM
            NN    = NGRID**(NDIM-idim)
            ibin_dim(idim) = (ibin - 1 - ibin_off)/NN + 1
            ibin_off       = ibin_off + (ibin_dim(idim) - 1) * NN

            ipar     = ipar_dim(idim)  ! fetch fit par index
            igrid    = ibin_dim(idim)
            TMP      = float( igrid ) - 0.5

            XTMP     = PARVAL_MIN(ipar)
     &               + PARVAL_BINSIZE(ipar) * TMP

            PARVAL(ipar)            = XTMP
            PARVAL_GRID(igrid,ipar) = XTMP

         enddo  ! end loop of NDIM

c get X8 array that contains only parameters to integrate
c (fixed parameters are weeded out from PARVAL)

         CALL FITVAL_FLOAT(PARVAL, NDIM, X8) ! returns NDIM and X8

         PDF   = FCNPDF(NDIM,X8)   ! evaluate normalized PDF

         NEVAL = NEVAL + 1         ! increment # function calls

         IF ( PDF .EQ. 0.0 ) goto 771

         LPDFZERO = .FALSE.

         PDFSUM   = PDFSUM + PDF  ! increment total integral

         do idim  = 1, NDIM
            ipar  = ipar_dim(idim)  ! fetch fit par index

            PDFWSUM(ipar) = PDFWSUM(ipar) + PDF * PARVAL(ipar)

            do idim2 = 1, NDIM
               ipar2 = ipar_dim(idim2)
               PDFWSUMCOR(ipar,ipar2) = PDFWSUMCOR(ipar,ipar2)
     &                + PDF * PARVAL(ipar) * PARVAL(ipar2)
            enddo

c sum pdf separately for each grid point and for each IPAR
c so that 1-dim PDF can be plotted for each IPAR.

            igrid = ibin_dim(idim)
            PDFSUM_GRID(igrid,ipar) =
     &      PDFSUM_GRID(igrid,ipar) + PDF

            if ( PDFSUM_GRID(igrid,ipar) .GT. PDFMAX(ipar) ) then
              PDFMAX(ipar) = PDFSUM_GRID(igrid,ipar)
            endif
         enddo  ! end of idim loop

          if ( PDF > 0.0 .and. HOFF > 0 ) then
            xpdf(1)   = DLOG10(PDF)
            xpdf(1)   = max ( -19.999, xpdf(1) )
            wgt       = 1.0
            CALL SNHIST_FILL(NHDIM, HOFF, XPDF, WGT )
          endif

771       continue
          if ( MOD(IBIN,10000)  .EQ. 0 ) then
             print*,'      Processing grid-bin ',
     &           ibin,'/', NBINTOT
             CALL FLUSH(6)
          endif

770   CONTINUE

      IF ( LPDFZERO ) THEN
        print*,' '
        print*,'  WARNING: INTEGPDF ERROR for CID=', SNLC_CCID
        print*,'  pdf function is zero everywhere with NGRID=',NGRID
        print*,' '
        IERR = -9

        IF ( OPT .EQ. 2 .and. ABORT_ON_MARGPDF0 ) THEN
          print*,' ***** ABORT ***** '
          CALL EXIT(EXIT_ERRCODE)
        ELSE
          RETURN
        ENDIF

      ENDIF

c ---------------------------------------
c fill histograms and PDFVAL_STORE array

      DO idim  = 1, NDIM
         ipar  = ipar_dim(idim)  ! fetch fit par index

         PDFVAL(ipar) = PDFWSUM(ipar) / PDFSUM

         DO igrid = 1, NGRID
            PDF = PDFSUM_GRID(igrid,ipar) / PDFMAX(ipar)

            if ( PDF .LT. 1.0E-30 ) THEN
              PDF1D(igrid,ipar) = 1.0E-20  ! avoid hbook bit problems
            else
              PDF1D(igrid,ipar) = PDF
            endif

         ENDDO  ! end of igrid loop

      ENDDO  ! end of IDIM loop

c determine PDF error (RMS) without using hbook so
c that we can pass HOFF=0 and skip histograms

      DO idim  = 1, NDIM
         ipar  = ipar_dim(idim)  ! fetch fit par index
         SUM0 = 0.0
         SUM1 = 0.0
         SUM2 = 0.0
         NPDF = 0
         PDFPROB2(ipar) = 0.0

      DO igrid = 1, NGRID

         XTMP   = PARVAL_GRID(igrid,ipar)
         PDFTMP = PDF1D(igrid,ipar)
         if ( PDFTMP .GT. 1.0E-6 ) NPDF = NPDF + 1

         SUM0   = SUM0 + PDFTMP
         SUM1   = SUM1 + PDFTMP * XTMP
         SUM2   = SUM2 + PDFTMP * XTMP * XTMP

         PDF_NBR1 = 0.0
         PDF_NBR2 = 0.0
         if ( igrid .GT. 1     )  PDF_NBR1 = PDF1D(igrid-1,ipar)
         if ( igrid .LT. NGRID )  PDF_NBR2 = PDF1D(igrid+1,ipar)

c check for 2nd local maximum
         if (    PDFTMP .LT. .99
     &     .and. PDFTMP .GT. PDF_NBR1
     &     .and. PDFTMP .GT. PDF_NBR2 ) then
            PDFPROB2(ipar) = PDFTMP
         endif
      ENDDO  ! igrid

        SQERR = SUM2/SUM0 - (SUM1/SUM0)**2

        if ( SQERR .LT. -0.00001 ) THEN ! allow for numerical rounding
                print*,' '
                print*,' SUM[0,1,2] = ', SUM0, SUM1, SUM2
                print*,' (SUM2/SUM0)     = ', SUM2/SUM0
                print*,' (SUM1/SUM0)**2  = ', (SUM1/SUM0)**2
                print*,' SQERR           = ', SQERR
                print*,' NPASS=',NPASS,'  OPT=',OPT
                c1err = ' SWERR < 0 for ' // PARNAME_STORE(ipar)
                CALL MADABORT("INTEGPDF", c1err, "  ")
         endif

c to compute error from RMS, require more than 1 PDF bin to be non-zero
c (to avoid pathologies from PDFERR -> 0)

         if ( SQERR .GT. 0.0 .and. NPDF .GT. 1 ) then
            PDFERR(ipar) = SQRT( SQERR )
         else
            PDFERR(ipar) = FITERR(ipar,iter)  ! PDF err = fit err for now
         endif

         ERRTYPE(ipar) = ERRTYPE_MARG
      ENDDO  ! idim


C -------------------------------------------------
C evaluate covariances

      DO 400 idim  = 1, NDIM
         ipar      = ipar_dim(idim)
      DO 401 idim2 = 1, NDIM
         ipar2     = ipar_dim(idim2)

         E12   = PDFWSUMCOR(ipar,ipar2)/PDFSUM
         E1xE2 = PDFVAL(ipar)*PDFVAL(ipar2)
         PDFERRMAT(ipar,ipar2) = E12 - E1xE2

         SQERR = PDFERR(ipar)*PDFERR(ipar2)
         PDFCORMAT(ipar,ipar2) = PDFERRMAT(ipar,ipar2)/SQERR

401   CONTINUE
400   CONTINUE


c ------------------------
       IF ( LDMP_DEBUG ) THEN

          print*,' xxx ====================================== '
          PRINT*,' xxx NPASS = ', NPASS

         DO idim  = 1, NDIM
            ipar  = ipar_dim(idim)

            print*,' - - - - - - - - - - - - - - - - - '
            write(6,665) PARNAME_STORE(ipar),
     &      PDFVAL(ipar), PDFERR(ipar), PDFPROB2(ipar)

            write(6,666) PARNAME_STORE(ipar),
     &      PARVAL_MIN(ipar), PARVAL_MAX(ipar)

            write(6,667) 'PARVAL',
     &           ( PARVAL_GRID(igrid,ipar), igrid=1,11)
            write(6,667) 'PDFVAL',
     &           ( PDF1D(igrid,ipar), igrid=1,11)

665        format(T3, 'xxx ',A6, 2x, 'PDFVAL = ',
     &          G10.3,' +- ', G10.3, 3x, 'PROB2=',F5.3 )
666        format(T3, 'xxx ',A6, 2x, 'PARDIF(MIN,MAX)=',2F9.3)

667        format(T3,'xxx ',A, '=', 11F7.3 )
           CALL FLUSH(6)
         ENDDO
       ENDIF
c ------------------------

c  ------------------------------------------------------
c always go back to start to check if we have converged

           goto 2

c ==================================================
c Check option to plot PDF for each floated parameter

800   CONTINUE
      CALL FLUSH(6)

      IF ( HOFF .LE. 0 ) RETURN

      DO idim  = 1, NDIM
         ipar  = ipar_dim(idim)  ! fetch fit par index
         hid   = HOFF + ipar

         LL = index ( PARNAME_STORE(ipar), ' ' ) - 1
         write(chis,21)
     &          PARNAME_STORE(IPAR)(1:LL)
     &        , PARNAME_STORE(IPAR)(1:LL)
     &        , SNLC_CCID(1:ISNLC_LENCCID), char(0)

21       format(' margin. PDF( ',A,'-',A,'(fit) ) for CID=',A, A)


         TMPVAL    = FITVAL(ipar,NFIT_ITERATION)
         xmin(1)   = PARVAL_MIN(ipar) - TMPVAL
         xmax(1)   = PARVAL_MAX(ipar) - TMPVAL
         NB(1)     = NGRID

         CALL SNHIST_INIT(NHDIM, HID, CHIS//char(0),
     &           NB, XMIN, XMAX, LEN(chis) )

         DO igrid = 1, NGRID
           TMP      = DBLE(igrid) - 0.5
           XVAL(1)  = XMIN(1) + PARVAL_BINSIZE(ipar) * TMP
           WGT      = PDF1D(igrid,ipar)
           CALL SNHIST_FILL( NHDIM, HID, XVAL, WGT )
         ENDDO

      ENDDO

      RETURN
      END   ! end of INTEGPDF


C =======================================
CDECK  ID>,  INTEGRANGE. 
      SUBROUTINE INTEGRANGE(IPAR,NGRID,NSIGMA,PDFLAST,
     &      LREDO,RANGE)

c
c Created Apr 30, 2007 by R.Kessler
c
c Determine integration range for IPAR parameter based on
c 1-dim PDF values from previous integration.
c
c On first pass, RANGE(1)=RANGE(2)=0 and integration range
c is just based on NSIGMA * FITERR from MINUIT.
c
c Oct 23, 2007: TMP_PROB -> min (0.98, GRIDPROB)
c               to avoid dividing by ln(near 1)
c
c Dec 3, 2007:  min(0.98,GRIDPROB) -> min(0.95,GRIDPROB)
c               so that integ-range is not opened so much
c               (short-term fix for photoZ fit to 14888)
c
c Oct 17, 2009: define PDFLAST_MAX = .95 with mutiple PDF bins,
c               or =.5 with just one PDF bin. Avoids severe bin-
c               extensions when there is just one non-zero PDF bin.
c
c               Makes sure that RANGE(1:2) is withing INIBND
c
c Dec 16, 2011:
c    - write more info on PDFPROBLEM at endge of 1 dim PDF.
c    - for PHOTOZ, skip upper INIBND check on RANGE(2)
c
c -----------------------------------

      IMPLICIT NONE

c subroutine args

      INTEGER
     &   IPAR   ! (I) parameter to determine integration range
     &  ,NGRID  ! (I) number of grid points to integrate

      REAL*8
     &   NSIGMA          ! (I)
     &  ,PDFLAST(NGRID)  ! (I) 1-dim PDF at grid points of last integration
     &  ,RANGE(2)        ! (I,O) integration limits: old -> new

      LOGICAL LREDO      ! (I) flag to redo integration

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      LOGICAL
     &   LSYMERR
     &  ,LTMP
     &  ,LPDFMAX
     &  ,BADEDGE(2)
     &  ,LFIRST
     &  ,USE_PDFERR

      INTEGER
     &   NREDO
     &  ,N1D_TOT           ! total number of 1D bins = NGRID
     &  ,N1D_PROB0         ! number of 1D bins with negligible prob
     &  ,NPDF_GOOD
     &  ,igrid
     &  ,igrid_min
     &  ,igrid_max
     &  ,L1, L2, i
     &  ,ITER

      REAL*8
     &   XNSIG, XNGRID, xgrid
     &  ,RANGE_OLD(2)
     &  ,RANGE_NEW(2)
     &  ,BINSIZE_OLD
     &  ,BINSIZE_NEW
     &  ,TMP_PLUS
     &  ,TMP_MINUS
     &  ,TMP_SIG
     &  ,TMP_PROB
     &  ,TMP_EDGE
     &  ,TMP_PDF
     &  ,TMP_VAL
     &  ,SHIFT, BND
     &  ,PDFMAX_atEDGE
     &  ,PDFLAST_MAX

      CHARACTER PDFPROBLEM(40)*48

C -------------- BEGIN -------------

      ITER = NFIT_ITERATION

c init a bunch of stuff.

      XNSIG         = NSIGMA
      XNGRID        = FLOAT(NGRID)

      LFIRST = (RANGE(1) .EQ. 0.0 .and. RANGE(2) .EQ. 0.0)

c store old integration range since it gets over-written later.
      RANGE_OLD(1) = RANGE(1)
      RANGE_OLD(2) = RANGE(2)
      BINSIZE_OLD  = (RANGE_OLD(2)-RANGE_OLD(1))/XNGRID

      NREDO        = 0
      LREDO        = .FALSE.  ! output arg !!
      TMP_PLUS     = 0.0
      TMP_MINUS    = 0.0

      IF ( LFIRST ) THEN

         USE_PDFERR = PDFERR(ipar) .GT. 0.0
         LSYMERR = abs(FITERR_RATIO(ipar,ITER)-1.0) .LT. 0.20

         IF ( USE_PDFERR ) THEN  ! PDF error gives better estimate
           TMP_PLUS    =  XNSIG * PDFERR(ipar)
           TMP_MINUS   = -XNSIG * PDFERR(ipar)  ! neg number
         ELSE IF ( LSYMERR ) THEN
           TMP_PLUS    =  XNSIG * FITERR(ipar,ITER)
           TMP_MINUS   = -XNSIG * FITERR(ipar,ITER)  ! neg number
         ELSE
           TMP_PLUS    =  XNSIG * FITERR_PLUS(ipar,ITER)
           TMP_MINUS   =  XNSIG * FITERR_MINUS(ipar,ITER)  ! neg number
         ENDIF

         RANGE(1) = FITVAL(ipar,ITER) + TMP_MINUS
         RANGE(2) = FITVAL(ipar,ITER) + TMP_PLUS

         LREDO = .TRUE.
         RETURN

      ENDIF

c ---------------------------------------------------
c loop over grid points and find bin with first,last
c non-negligible PDF value.
c Also count NPDF_GOOD = number of bins with PDF > PDFMIN

      N1D_TOT    = 0
      N1D_PROB0  = 0
      LPDFMAX    = .FALSE.
      igrid_min  = 1
      igrid_max  = NGRID

      DO 100 igrid = 1, NGRID

         TMP_PDF = PDFLAST(igrid)
         if ( TMP_PDF .GT. 0.90 ) LPDFMAX = .TRUE.

         N1D_TOT = N1D_TOT + 1

         if ( TMP_PDF .GT. PDFMIN_GOOD ) then
             NPDF_GOOD = NPDF_GOOD + 1
         else
             N1D_PROB0 = N1D_PROB0 + 1

             if ( LPDFMAX .and. IGRID_MAX .EQ. NGRID ) then
                igrid_max = igrid  ! first negligible pdf past max
             endif

             if ( .not. LPDFMAX ) then
                igrid_min = igrid  ! last negligible pdf before max
             endif
         endif

100   CONTINUE  ! end of igrid loop

      IF ( NPDF_GOOD .GT. 1 ) THEN
          PDFLAST_MAX = 0.95
      ELSE
          PDFLAST_MAX = 0.80  ! Guass approx is bad with just one bin
      ENDIF


c -----------------------------------------------------------
c if PDF at edge is too big, then compute adjustment to extend edge.
c Adjustent is based on assumption of Gaussian profile.

      SHIFT      = PDFVAL(ipar) - FITVAL(ipar,ITER)
      BADEDGE(1) = .FALSE.
      BADEDGE(2) = .FALSE.
      PDFMAX_atEDGE = MAX ( PDFLAST(1), PDFLAST(NGRID) )

      LTMP = PDFLAST(1) .GT. PDFMAX_EDGE
      IF ( LTMP  ) THEN
         BADEDGE(1) = .TRUE.
         TMP_PROB   = min ( PDFLAST(1), PDFLAST_MAX )
         TMP_EDGE   = RANGE_OLD(1) - PDFVAL(ipar) ! distance to min edge
         TMP_SIG    = TMP_EDGE / SQRT ( -2.0 * DLOG(TMP_PROB) )
         TMP_MINUS  = XNSIG * TMP_SIG - TMP_EDGE

c avoid making integration window smaller
         if ( TMP_MINUS .GT. 0.0 ) then
              TMP_MINUS = -abs(3.*SHIFT)
         endif
      ENDIF



      LTMP = PDFLAST(NGRID) .GT. PDFMAX_EDGE
      IF ( LTMP ) THEN
          BADEDGE(2) = .TRUE.
          TMP_PROB   = min ( PDFLAST(NGRID), PDFLAST_MAX )
          TMP_EDGE   = RANGE_OLD(2) - PDFVAL(ipar) ! distance to edge
          TMP_SIG    = TMP_EDGE / SQRT ( -2.0 * DLOG(TMP_PROB) )
          TMP_PLUS   = XNSIG * TMP_SIG - TMP_EDGE

c avoid making integration window smaller
          if ( TMP_PLUS .LT. 0.0 ) then
               TMP_PLUS = +abs(3.*SHIFT)
          endif
      ENDIF

c ----------------------------
c update new integration range to account for
c extended range(s).

      RANGE_NEW(1) = RANGE_OLD(1) + TMP_MINUS
      RANGE_NEW(2) = RANGE_OLD(2) + TMP_PLUS
      BINSIZE_NEW  = (RANGE_NEW(2)-RANGE_NEW(1))/XNGRID

c -------------------------------------
c check for bins that have ~0 prob, and reduce integration
c range to eliminate these 0-prob bins.

      if ( igrid_min .GT. 1 ) then
         xgrid        = float(igrid_min) - 0.5
         TMP_VAL      = RANGE_OLD(1) + BINSIZE_OLD * xgrid
         RANGE_NEW(1) = TMP_VAL - BINSIZE_NEW/2.0
      endif

      if ( igrid_max .LT. NGRID ) then
         xgrid        = float(igrid_max) - 0.5
         TMP_VAL      = RANGE_OLD(1) + BINSIZE_OLD * xgrid
         RANGE_NEW(2) = TMP_VAL + BINSIZE_NEW/2.0
      endif

c store NEW integration range in output subroutine arg.

      RANGE(1) = RANGE_NEW(1)
      RANGE(2) = RANGE_NEW(2)

c ---------------------------------------------------
c check of there is any reason that integration needs to be redone.
c  - Prob(edge) is too high
c  - Only 1 bin in 1D PDF
c  - Too many Zero-prob bins'
c
c  Set LREDO flag = T if there is a problem.

      IF ( BADEDGE(1)  ) then
           NREDO = NREDO + 1
           write(pdfproblem(NREDO),441) PDFLAST(1), 'lo'
           NREDO = NREDO + 1
           write(pdfproblem(NREDO),1441) RANGE_OLD, RANGE_NEW
      ENDIF
      IF ( BADEDGE(2)  ) then
           NREDO = NREDO + 1
           write(pdfproblem(NREDO),441) PDFLAST(NGRID), 'hi'
           NREDO = NREDO + 1
           write(pdfproblem(NREDO),1441) RANGE_OLD, RANGE_NEW
      ENDIF

441        format('PROB=',F6.4, ' at ',A,' edge of 1 dim PDF')
1441       format('RANGE=(', F6.2, ',', F6.2, ')' , ' -> ',
     &                  '(', F6.2, ',', F6.2, ')'   )  ! Dec 2011

      IF ( NPDF_GOOD .LT. 3  ) then
           NREDO = NREDO + 1
           write(pdfproblem(NREDO),442)
442        format('<= 2 non-zero PDF bins.' )
      ENDIF

      IF ( N1D_PROB0 .GT. 3 ) THEN
           NREDO = NREDO + 1
           write(pdfproblem(NREDO),443) N1D_PROB0, N1D_TOT
443        format('PROB=0 for ', I3, '/' , I3, 2x,
     &           'PDF bins' )
      ENDIF

c ----------------------------------------------
c print list of PDF-problems to STDOUT

      IF ( NREDO .GT. 0 ) THEN

         LREDO = .TRUE.

         L1 = index ( PARNAME_STORE(ipar), ' ' ) - 1
         L2 = index ( SNLC_CCID, ' ' ) - 1

         do i = 1, NREDO
            write(6,449)
     &          PARNAME_STORE(ipar)(1:L1)
     &        , SNLC_CCID(1:L2)
     &        , PDFPROBLEM(i)
449         format(T8,A,'-PDF PROBLEM(',A,') : ', A)
         enddo

      ENDIF

c don't allow range to go outside of official INIBND range.

      BND = INIBND(1,IPAR)
      IF (RANGE(1) .LT. BND ) RANGE(1) = BND

c special exception for PHOTOZ
      IF ( PARNAME_STORE(IPAR)(1:6) .NE. 'PHOTOZ' ) THEN
        BND = INIBND(2,IPAR)
        IF (RANGE(2) .GT. BND ) RANGE(2) = BND
      ENDIF

      RETURN
      END

C =======================================
CDECK  ID>,  FCNPDF. 
      DOUBLE PRECISION FUNCTION FCNPDF(NDIM,X)
c
c  Retruns exp[ - (chi2 - chi2min) / 2 ]
c
c  where CHI2 is returned from a call to FCNSNLC.
c  This function is designed to accept only the
c  floated parameters so that it can be used by
c  more generic integration routines that don't
c  know about fixed parameters.
c
c Example: fit-params 1,2 are fixed and 3-6 float.
c          Then pass NDIM=4 and X(4) = array of floated parameters.
c
c -----------------------
      IMPLICIT NONE

c function input

      INTEGER NDIM     ! (I) number of dimensions
      REAL*8  X(NDIM)  ! (I) args for chi2-function

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &   ipar_all
     &  ,ipar_float
     &  ,ipar

c FCNSNLC args

      INTEGER IFLAG

      DOUBLE PRECISION
     &    GRAD(MXFITPAR)
     &   ,FITVAL_LOC(MXFITPAR)
     &   ,CHI2, DELCHI2
     &   ,USRFUN

      EXTERNAL USRFUN

C ---------- BEGIN -----------------

      FCNPDF  = 0.0
      IFLAG   = FCNFLAG_FAST

c restore input parameters X to local FITVAL array;
c note that fixed parameters are loaded from FITVAL_STORE array.

      ipar_float = 0

      DO ipar_all = 1, NFITPAR_MN

        if ( FLOATPAR(ipar_all)  ) then  ! is a floated param
           ipar_float = ipar_float + 1
           FITVAL_LOC(ipar_all) = X(ipar_float)
        else
           FITVAL_LOC(ipar_all) = FITVAL(ipar_all,NFIT_ITERATION)
        endif

      ENDDO

c      write(6,20) (FITVAL_LOC(ipar), ipar=1, 6)

      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2,FITVAL_LOC,IFLAG,USRFUN)

c set FCNPDF only if FCN function did not have its
c chi2 got too big.

      if ( chi2 .LE. FITCHI2_QUIT ) then
         DELCHI2 = chi2 - FITCHI2_MIN
         FCNPDF  = dexp(-DELCHI2/2.0)
      endif

      RETURN
      END  ! end of FCNPDF


C ==============================================
CDECK  ID>,  FITVAL_FLOAT. 
      SUBROUTINE FITVAL_FLOAT(FITVAL_LOC,NDIM,X)
c
c FITVAL is the array of NFITPAR_MN parameters.
c Returns NDIM = number of floated parmaters,
c and X(NDIM) = array of floated paramters.
c i.e, the fixed paramters are ignored.
c
c -----------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c declare function args

      REAL*8  FITVAL_LOC(*)     ! (I) fit parameters
      INTEGER NDIM              ! (O) number of floated params
      REAL*8  X(*)              ! (O) array of floated params

c local args
      INTEGER ipar
C --------------- BEGIN -------------

      NDIM = 0
      DO ipar = 1, NFITPAR_MN
        if ( FLOATPAR(ipar) ) then
           NDIM    = NDIM + 1
           X(NDIM) = FITVAL_LOC(ipar)
        endif
      ENDDO

      RETURN
      END


CDECK  ID>,  FITPAR_INI. 
      SUBROUTINE FITPAR_INI(IERR)
c
c User init: (read input, open files, etc ...)
c
c One time initialize BEFORE fitting and USRANA begins.
c
c
c Jul 19 2019: overhaul arguments to INIT_GENMAG_SNOOPY
c
c Aug 2 2019: pass full model name (including path) to INIT_GENMAG_SNOOPY,
c             instead of passing only the model name without path
c
c Jun 17 2020: if OPT_PHOTOZ==2, set ERRMAX_BAD(zPHOT) = 1.0E-8
c
c -------------------------------------
      IMPLICIT NONE

      INTEGER
     &   IERR    ! (O) 0 => OK

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


      LOGICAL  LTMP

      INTEGER
     &   ipar, ipar2, istat, len1, len2, len3, len4, len5, LL,j
     &  ,LEN_VERS, LEN_NAME

c variables for PARSE_FILTSTRING:
      INTEGER IAFILT(MXFILT_OBS), ifiltdef, ifiltr
      INTEGER NF_UNDEF, NF_DEF, NF_ABORT, NSURFACE
      REAL    XAFILT(MXFILT_OBS)
      REAL    ERRMAX

      CHARACTER
     &   snsed_file*(MXCHAR_FILENAME)
     &  ,cfilt*2
     &  ,cfilt_rest*(MXFILT_REST)
     &  ,cfilt_defined*(MXFILT_ALL)
     &  ,cfilt_undefined*(MXFILT_ALL)
     &  ,covFile*(MXCHAR_FILENAME)
     &  ,tmpName*(MXCHAR_FILENAME)
     &  ,ctmp*4
     &  ,chis*80

c args for GET_FLUX_FITFUN
      INTEGER isn, ifilt, ifilt_obs, opt, i, NFILT
      INTEGER ilam, NLAM, hid, OPTMASK
      REAL*4  Z4

c misc.
      REAL*8   DUM8, LAMRANGE8(2)

c define functions

      INTEGER
     &   INIT_GENMAG_STRETCH2  ! 1 or 2-par stretch
     &  ,INIT_GENMAG_MLCS2k2
     &  ,INIT_GENMAG_SNOOPY
     &  ,SNANA_NEARNBR_RDINPUT
     &  ,get_NSURFACE_SEDMODEL

      EXTERNAL
     &   INIT_GENMAG_STRETCH2
     &  ,INIT_GENMAG_MLCS2k2
     &  ,INIT_GENMAG_SNOOPY
     &  ,INIT_GENMAG_EXTINCTION

      REAL*8  GET_FLUX_FITFUN
      INTEGER FILTINDX

C ------------------- BEGIN ---------------------

      IERR = 0

      CALL RDFITNML(IERR)
      if ( IERR .NE. 0 ) RETURN

      CALL RDMCMCNML(IERR)
      if ( IERR .NE. 0 ) RETURN

c check for NN option (read &NNINP namelist)
      NVAR_NEARNBR = SNANA_NEARNBR_RDINPUT()

c set FITANA_CUTWIN_XXX for cuts that might change for photoZ fits.
c This allows using the same FITANA_CUTWIN_XXX array in FITANA

      DO i = 1, 2
       FITANA_CUTWIN_TREST(i)    = CUTWIN_TREST(i)
       FITANA_CUTWIN_TREST2(i)   = CUTWIN_TREST2(i)
       FITANA_CUTWIN_TRESTMIN(i) = CUTWIN_TRESTMIN(i)
       FITANA_CUTWIN_TRESTMAX(i) = CUTWIN_TRESTMAX(i)
       FITANA_CUTWIN_TGAPMAX(i)  = CUTWIN_TGAPMAX(i)
       FITANA_CUTWIN_T0GAPMAX(i) = CUTWIN_T0GAPMAX(i)
      ENDDO
c -------
c Default is rest-frame model; override below for obs-frame
      LOBS_FITMODEL  = .FALSE.
      LREST_FITMODEL = .TRUE.
      LSED_FITMODEL  = .FALSE.

c ---------------------------------
c set fitpar names.

      DO ipar = 1, MXFITSTORE
         write(PARNAME_STORE(ipar),20) ipar
20       format('BIDON', I3.3)
      ENDDO

      PARNAME_STORE(IPAR_ITER)    = 'ITER'

      PARNAME_STORE(IPAR_ISN)    = 'ISN'

c init to model that fits for extinction and MU;
c might be changed below, for example, for SALT2 model

      PARNAME_STORE(IPAR_AV)      = 'AV'
      ERRMAX_BAD(IPAR_AV)         = 0.005  ! 0.01->0.005  6/17/2020

      PARNAME_STORE(IPAR_DLMAG)   = 'DLMAG'
      ERRMAX_BAD(IPAR_DLMAG)      = 0.0

c check for floating RV in fit
      if ( INISTP_AVRV .GT. 0.0 ) then
        PARNAME_STORE(IPAR_AVRV)    = 'AVRV'
      else
        PARNAME_STORE(IPAR_RV)      = 'RV'
      endif

      PARNAME_STORE(IPAR_PEAKMJD) = 'PKMJD'

      IF ( INISTP_PHOTOZ .GT. 0.0 ) THEN
        IF ( INISTP_PHOTOZ == 1 ) THEN
           CALL ABORT_ON_CUTWIN_TREST()  ! Feb 2014
        ENDIF
        PARNAME_STORE(IPAR_ZPHOT)  = 'zPHOT'
      ELSE
        PARNAME_STORE(IPAR_ZPHOT)  = 'REDSHIFT'
      ENDIF

      IF ( OPT_PHOTOZ == 2 ) THEN
          ERRMAX_BAD(IPAR_ZPHOT)   =  1.0E-8 ! likely has specz prior, 6/2020
          PHOTOZ_ITER1_LAMRANGE(1) =  2000.  ! Dec 2023: include UV region
      ELSE
          ERRMAX_BAD(IPAR_ZPHOT) =  0.0005
      ENDIF
      ABORT_ON_BADZ           = .FALSE.

      IF ( LSIM_SNANA ) THEN
        do ipar = 1, IPAR_MAX
          USESIM_FITPAR(ipar) = .FALSE.
        enddo
        USESIM_FITPAR(IPAR_AV)      = USESIM_AV .or. USESIM_COLOR
        USESIM_FITPAR(IPAR_RV)      = USESIM_RV
        USESIM_FITPAR(IPAR_PEAKMJD) = USESIM_PEAKMJD
        USESIM_FITPAR(IPAR_SHAPE)   = USESIM_SHAPE.or.USESIM_LUMIPAR
        USESIM_FITPAR(IPAR_DLMAG)   = USESIM_DLMAG
        USESIM_FITPAR(IPAR_ZPHOT)   = USESIM_REDSHIFT

      ENDIF

c set default cut-windows to be wide open

      DO ipar = 1, IPAR_MAX
        CUTWIN_FITPAR(1,ipar) = -1.0E8
        CUTWIN_FITPAR(2,ipar) =  1.0E8

        CUTWIN_FITERRz1(1,ipar) = -0.001
        CUTWIN_FITERRz1(2,ipar) = +1.0E8

        DO ipar2 = 1, IPAR_MAX
           if ( ipar .eq. ipar2 ) then
             CUTWIN_FITCOV(1,ipar,ipar2) = -1.0E8
             CUTWIN_FITCOV(2,ipar,ipar2) = +1.0E8
           else
             CUTWIN_FITCOV(1,ipar,ipar2) = FITWIN_COV_OFFDIAG(1)
             CUTWIN_FITCOV(2,ipar,ipar2) = FITWIN_COV_OFFDIAG(2)
           endif
        ENDDO  ! end ipar2 loop

      ENDDO  ! end ipar loop
c ------------

      CALL LANDOLT_PREP()

c Parse filter lambda-shifts;
c OPT=0 to NOT error-check filter because Bessell-B
c is usually not an observer-frame filter.

      CALL PARSE_FILTSTRING(0, FILTLAM_SHIFT, NF_DEF, iafilt, xafilt )
      DO i = 1, NF_DEF
         ifiltdef            = IAFILT(i)
         FILTOBS_LAMSHIFT(ifiltdef) = xafilt(i)  ! global R*4 storage
      ENDDO

c ---------------------
c print WARNING if fitting subset of filters.
      Len1 = INDEX(SURVEY_FILTERS,' ') - 1
      Len2 = INDEX(FILTLIST_FIT,  ' ') - 1
      IF ( Len2 .LT. Len1 ) THEN
           print*,'  WARNING: fitting filter subset  ',
     &     FILTLIST_FIT(1:Len2),'  from  ', SURVEY_FILTERS(1:Len1)
      ENDIF


c -------------------------------------------------------
c Covariance matrix:
c construct name of covar_File for this version;
c if it does not exist, then set covFile = '' so that
c the default is used.

      if (   fitcovar_file .EQ. 'SIM'
     &  .or. fitcovar_file .EQ. 'sim' ) then

        len1    = INDEX(SNDATA_PREFIX, ' ' ) - 1
        fitcovar_file = SNDATA_PREFIX(1:len1) // '_COVAR.DAT'
      endif

c check option to fit restmags.
      CALL FITRESTMAG_INI()

c check option to fit obsMag 2 different ways
      CALL FITMAGDIF_INI()

c check option to include IDEAL fit with FLUX=TRUEFLUX (no Poisson fluctuations)
      CALL SIMFIT_IDEAL_INI()

c ------------------------------------------------------
c set FITMODEL_INDEX, FITMODEL_PATH and FITMODEL_VERSION

      CALL FITMODEL_INI()

      LEN_VERS = INDEX(FITMODEL_VERSION, ' ' ) - 1
      LEN_NAME = INDEX(FITMODEL_NAME,' ') - 1

      tmpName  = FITMODEL_NAME(1:LEN_NAME) // char(0)

c set rest-frame filter ranges.
      FILTLIST_MODEL = ''
      NFILT_MODEL    = 0

      NSHAPEPAR = 1  ! default is 1 shape-par unless changed below

      LL = INDEX(SNDATA_ROOT,' ') - 1

      IF (   FITMODEL_INDEX .EQ. MODEL_STRETCH
     &  .or. FITMODEL_INDEX .EQ. MODEL_STRETCH2 ) THEN


         RESTLAMBDA_MODEL(1) = 3000.0
         RESTLAMBDA_MODEL(2) = 9500.0

         ISTAT = INIT_GENMAG_STRETCH2(tmpName,CFILT_REST,LEN_NAME,LEN2)

         if ( FITMODEL_INDEX .EQ. MODEL_STRETCH ) then
           PARNAME_STORE(IPAR_SHAPE) = 'STRETCH'
         else
           PARNAME_STORE(IPAR_SHAPE)  = 'SRISE'
           PARNAME_STORE(IPAR_SHAPE2) = 'SFALL'
           NSHAPEPAR = 2
         endif

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN

         LOBS_FITMODEL  = .TRUE.
         LREST_FITMODEL = .FALSE.
         LSED_FITMODEL  = .TRUE.

         PARNAME_STORE(IPAR_COLOR)  = 'c'
         ERRMAX_BAD(IPAR_COLOR)     = 0.001

         PARNAME_STORE(IPAR_SHAPE)  = 'x1'
         ERRMAX_BAD(IPAR_SHAPE)     =  0.001

         PARNAME_STORE(IPAR_SHAPE2)  = 'x2'    ! Dec 2023
         ERRMAX_BAD(IPAR_SHAPE2)     =  0.0001

         if ( OPT_SALT2FIT .EQ. 0 .or. OPT_SALT2FIT .EQ. 4) then   !default
           PARNAME_STORE(IPAR_X0)         = 'x0'
         else if ( OPT_SALT2FIT .EQ. 1 ) then
           PARNAME_STORE(IPAR_X0)         = 'logx0'
         else if ( OPT_SALT2FIT .EQ. 2 ) then
           PARNAME_STORE(IPAR_X0)         = 'MUDIF'
         else
           write(c1err,669) OPT_SALT2FIT
669        format('Invalid OPT_SALT2FIT = ',I5 )
           c2err = 'Check &FITINP namelist'
           CALL MADABORT("FITPAR_INI", c1err, c2err )
         endif
         ERRMAX_BAD(IPAR_X0)        = 0.0

c note that mB is computed from fitpars, and does not float in fit
         PARNAME_STORE(IPAR_MB)         = 'mB'

         CALL SEDMODEL_INI(0,IERR)

         NSURFACE = get_NSURFACE_SEDMODEL()
         if ( NSURFACE == 3 ) THEN
             NSHAPEPAR = 2
             INISTP_SHAPE2 = 0.1
             INIVAL_SHAPE2 = 0.01
         endif

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_BAYESN ) THEN

         LOBS_FITMODEL  = .TRUE.
         LREST_FITMODEL = .FALSE.
         LSED_FITMODEL  = .TRUE.

         PARNAME_STORE(IPAR_COLOR)  = 'AV'
         ERRMAX_BAD(IPAR_COLOR)     = 0.001

         PARNAME_STORE(IPAR_SHAPE)  = 'THETA'
         ERRMAX_BAD(IPAR_SHAPE)     =  0.001

         PARNAME_STORE(IPAR_DLMAG)  = 'DLMAG'
         ERRMAX_BAD(IPAR_DLMAG)     = 0.0

         CALL SEDMODEL_INI(0,IERR)

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SIMSED ) THEN

         LOBS_FITMODEL  = .TRUE.
         LREST_FITMODEL = .FALSE.
         LSED_FITMODEL  = .TRUE.

         PARNAME_STORE(IPAR_X0)     = 'MUDIF'
         ERRMAX_BAD(IPAR_X0)        = 0.0

         CALL  SEDMODEL_INI(0,IERR)

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_MLCS2k2 ) THEN

         PARNAME_STORE(IPAR_SHAPE)  = 'DELTA'
         ERRMAX_BAD(IPAR_SHAPE) = 0.02

         len2 = INDEX(fitcovar_file, ' ' ) - 1
         len3 = 0

         COVFILE = FITCOVAR_FILE(1:len2) // CHAR(0)

         ISTAT = INIT_GENMAG_MLCS2k2(
     &               tmpName, covFile, scale_covar,
     &               FILTLIST_MODEL, LEN_VERS,len2,len3
     &                      )

c fetch valid lambda-range from mlcs-function; note that the range
c depends on which IR filters are used.

         CALL GET_LAMRANGE_MLCS2k2(LAMRANGE8(1),LAMRANGE8(2))
         RESTLAMBDA_MODEL(1) = LAMRANGE8(1)
         RESTLAMBDA_MODEL(2) = LAMRANGE8(2)

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SNOOPY ) THEN


         CALL GET_LAMRANGE_snoopy(LAMRANGE8(1),LAMRANGE8(2))
         RESTLAMBDA_MODEL(1) = LAMRANGE8(1)
         RESTLAMBDA_MODEL(2) = LAMRANGE8(2)
         PARNAME_STORE(IPAR_SHAPE) = 'STRETCH'
         OPTMASK = 0
         ISTAT = INIT_GENMAG_SNOOPY(tmpName, OPTMASK,
     &       FILTLIST_MODEL, LEN_NAME, len2 )  ! return args

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_FIXMAG ) THEN

         PARNAME_STORE(IPAR_SHAPE) = 'NULL'
         FILTLIST_MODEL = "UBVRI"

         print*,' '
         print*,' Invalid FIXMAG model.'
         print*,' Program Stopping Gracefully. '
         print*,' '
         STOP

      ELSE
         c1err = 'Invalid FITMODEL_NAME: ' // FITMODEL_NAME(1:40)
         c2err = 'Check &FITINP namelist'
         CALL MADABORT("FITPAR_INI", c1err, c2err )
      ENDIF

c check for simulated efficiency map to use as prior
      CALL INIT_PRIOR_SIMEFF

C ============================================
c load IFILTMAP_MODEL array and its inverse
c Mar 2013: abort if model filter is not defined in kcor table.

      DO i       = 1, MXFILT_ALL
        IFILTMAP_MODEL(i)    = -9
        IFILTINVMAP_MODEL(i) = -9
      ENDDO
      NFILT_MODEL = INDEX(FILTLIST_MODEL, ' ' ) - 2 ! subtract 2 for char(0)
      CFILT = ''
      CFILT_DEFINED = ''
      CFILT_UNDEFINED = ''
      NF_UNDEF = 0  ! number of undefined filters
      NF_DEF   = 0
      DO i       = 1, NFILT_MODEL
        CFILT    = FILTLIST_MODEL(i:i)
        ifiltdef = FILTINDX(cfilt)   ! absolute index of model filter
        IFILTMAP_MODEL(i)           = ifiltdef
        IFILTINVMAP_MODEL(ifiltdef) = i

        ifiltr  = IFILTDEF_INVMAP_REST(IFILTDEF)
        IF ( ifiltr < 0 ) then
           NF_UNDEF = NF_UNDEF + 1
           CFILT_UNDEFINED = CFILT_UNDEFINED(1:NF_UNDEF-1) // CFILT(1:1)
        ELSE
           NF_DEF = NF_DEF + 1
           CFILT_DEFINED = CFILT_DEFINED(1:NF_DEF-1) // CFILT(1:1)
        ENDIF
      ENDDO


c -----------
c set optional filter-dependent cuts on TREST
      CALL SETCUTS_FITWIN_TREST

c ----------------------------------------------

      CUTWIN_FITPAR(1,IPAR_PEAKMJD) = FITWIN_MJD(1)  ! 9/16/2016
      CUTWIN_FITPAR(2,IPAR_PEAKMJD) = FITWIN_MJD(2)
      CUTWIN_FITPAR(1,IPAR_SHAPE) = FITWIN_SHAPE(1)
      CUTWIN_FITPAR(2,IPAR_SHAPE) = FITWIN_SHAPE(2)
      CUTWIN_FITPAR(1,IPAR_AV)    = FITWIN_COLOR(1)
      CUTWIN_FITPAR(2,IPAR_AV)    = FITWIN_COLOR(2)
      CUTWIN_FITPAR(1,IPAR_ZPHOT) = FITWIN_ZPHOT(1)
      CUTWIN_FITPAR(2,IPAR_ZPHOT) = FITWIN_ZPHOT(2)

c cuts on offDiag cov already set since it's the same cut on each element.
c Here set diagonal cuts for each fitPar.

      IPAR = IPAR_PEAKMJD ; ERRMAX = FITWIN_PEAKMJD_ERR(2)
      CUTWIN_FITCOV(2,IPAR,IPAR) = ERRMAX*ERRMAX
      CUTWIN_FITERRz1(2,IPAR)    = FITWIN_PEAKMJD_ERRz1(2)

      IPAR = IPAR_MB ; ERRMAX = FITWIN_MB_ERR(2)
      CUTWIN_FITCOV(2,IPAR,IPAR) = ERRMAX*ERRMAX
      CUTWIN_FITERRz1(2,IPAR)    = FITWIN_MB_ERRz1(2)

      IPAR = IPAR_SHAPE ; ERRMAX = FITWIN_SHAPE_ERR(2)
      CUTWIN_FITCOV(2,IPAR,IPAR) = ERRMAX*ERRMAX
      CUTWIN_FITERRz1(2,IPAR)    = FITWIN_SHAPE_ERRz1(2)

      IPAR = IPAR_COLOR ; ERRMAX = FITWIN_COLOR_ERR(2)
      CUTWIN_FITCOV(2,IPAR,IPAR) = ERRMAX*ERRMAX
      CUTWIN_FITERRz1(2,IPAR)    = FITWIN_COLOR_ERRz1(2)

c determin RESTLAMBDA_USEFIT based on user FITRANGE and that
c defined by the model
      RESTLAMBDA_USEFIT(1) =
     &     MAX(RESTLAMBDA_MODEL(1),RESTLAMBDA_FITRANGE(1))
      RESTLAMBDA_USEFIT(2) =
     &     MIN(RESTLAMBDA_MODEL(2),RESTLAMBDA_FITRANGE(2))

      print*,'  '
      write(6,350) 'SN-MODEL', RESTLAMBDA_MODEL
      write(6,350) 'USER-DEF', RESTLAMBDA_FITRANGE
      write(6,350) 'Final   ', RESTLAMBDA_USEFIT
350   format(T5, A, 2x, 'LAMBDA RANGE: ', F6.0,' - ', F6.0 )

c abort if range makes no sense
      IF( RESTLAMBDA_USEFIT(2) .LT. 1000. ) THEN
         c1err = 'Invalid LAMBDA RANGE (see above).'
         c2err = 'Something is messed up.'
         CALL MADABORT("FITPAR_INI", c1err, c2err )
      ENDIF

c print cuts to reject epochs at 2nd epoch

      print*,'  '
      print*,'  SECOND-ITERATION EPOCH-REJECTION CUTS: '
      print*,'    REJECT  delchi2      > ', DELCHI2_REJECT
      print*,'    REJECT  signal/noise < ', SIGNOISE_REJECT
      print*,'    REJECT  Trest        < ', FITWIN_TREST(1)
      print*,'    REJECT  Trest        > ', FITWIN_TREST(2)
      print*,'    REJECT  MJD          < ', FITWIN_MJD(1)
      print*,'    REJECT  MJD          > ', FITWIN_MJD(2)
      print*,'  '

      print*,' '
      print*,'  FINAL FIT CUTS: '
      print*,'    REQUIRE MINOS ERROR for DLAMG        : ',
     &                 MINOS_ERR_DLMAG
      print*,'    REQUIRE MINOS ERROR for ALL   FITPAR : ',
     &                 MINOS_ERR_REQALL0
      print*,'    REQUIRE MINOS ERROR for ALL-1 FITPAR : ',
     &                 MINOS_ERR_REQALL1
      print*,'    FIT-SIGMACHI2     > ', FITWIN_CHI2SIGMA(1)
      print*,'    FIT-PROB(final)   > ', FITWIN_PROB(1)
      print*,'    FIT-PROB(no marg) > ', FITWIN_NOMARG_PROB(1)

      if ( NEARFILT_IGNORE_REST .NE. ' ' ) then
          print*,'    IGNORE NEAREST REST-FRAME FILTERS: ',
     &            NEARFILT_IGNORE_REST
      endif

      if ( DOFIT_PHOTOZ ) then
        print*,'    REQUIRE photoZ(SN-host) pull :',
     &                 FITWIN_ZPULL(1),' to ', FITWIN_ZPULL(2)
        CALL PHOTOZ_ANA(0,0,ISTAT) ! init ZDROP for each filter

      endif

      print*,'  '

c print ERRMAX_BAD

      DO ipar = 1, IPAR_MAX

         if ( .not. MINOS_ERRMAX_BAD ) ERRMAX_BAD(ipar) = 0.0

         write(6,88) PARNAME_STORE(ipar), ERRMAX_BAD(ipar)
88       format(T5,'Valid ERROR(', A10, ') must be > ', F9.5 )
      ENDDO
      print*,'  '

c ------------------
c check FUDGE_FITERR to see if some flux-errors should be
c blown up. Set logical(s) DOFUDGE_FITERR(ifilt_obs) to use later.

      CALL INIT_FUDGE_FITERR

c -----------------------------------------------
c initialize priors

      CALL FITINI_PRIORS

c rest-frame init
      IF ( LREST_FITMODEL ) THEN
         CALL INIT_GENMAG_EXTINCTION(OPT_SNXT)
      ENDIF

c -------------------------------------------
c Define extra "TABLEVAR" variables for output tables

      CALL FITINI_TABLEVAR

c check for file with interpolated MAGS at specified MJDs.

      IF ( N_INTERP_MJDLIST .GT. 0 ) THEN
         CALL DMP_SNMJD_INTERP(0,0)
      ENDIF

c check for option to compuare Zmax/Vmax
      CALL VMAX_INI()

c ----
      CALL FITINI_EPVAR(-1)

      RETURN
      END  ! end of FITPAR_INI

C ===========================================
CDECK  ID>,  FITPAR_INI2. 
      SUBROUTINE FITPAR_INI2(IERR)
c
c Created May 2012 by R.Kessler
c One-time Initialization after 1st event is read
c but before the fit is performed.
c
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IERR ! (O) 0=OK

      INTEGER ipar
      REAL*8    DUMPAR
      CHARACTER FNAM*12
C ------------- BEGIN ----------------
      IERR = 0
      FNAM = 'FITPAR_INI2'
c ------------------------------------------------
c Determine which parameters are floated in fit.
c Use namelist input since the global INISTP array has
c not yet been filled.

      do ipar = 1, IPAR_MAX
         FLOATPAR(ipar) = .TRUE.
      enddo
      FLOATPAR(IPAR_ITER) = .FALSE.
      FLOATPAR(IPAR_ISN)  = .FALSE.

      IPAR = IPAR_AV
        if (INISTP_AV     .EQ. 0.0 ) FLOATPAR(IPAR) = .FALSE.
      IPAR = IPAR_RV
        if (INISTP_RV     .EQ. 0.0 ) FLOATPAR(IPAR) = .FALSE.
      IPAR = IPAR_ZPHOT
        if (INISTP_PHOTOZ .EQ. 0.0 ) FLOATPAR(IPAR) = .FALSE.

      IPAR = IPAR_SHAPE
        if (INISTP_SHAPE.  EQ. 0.0 ) FLOATPAR(IPAR) = .FALSE.
      IPAR = IPAR_SHAPE2
        if (INISTP_SHAPE2. EQ. 0.0 ) FLOATPAR(IPAR) = .FALSE.

      IPAR = IPAR_DLMAG
        if (INISTP_DLMAG  .EQ. 0.0 ) FLOATPAR(IPAR) = .FALSE.

      IF ( OPT_TABLE(ITABLE_FITRES) > 0 ) THEN
         CALL TABLE_SNFIT(IDTABLE_FITRES,IFLAG_INI)
      ENDIF

      IF ( OPT_TABLE(ITABLE_MODELSPEC) > 0 .and.
     &     FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
         CALL TABLE_SNSPEC_SALT2(0)
      ENDIF

      IF ( SALT2_DICTFILE .NE. ' ' ) THEN
         CALL DMP_DICTFILE(0)  ! init dictFile
      ENDIF

      RETURN
      END  ! end FITPAR_INI2

C ===========================================
CDECK  ID>,  FITPAR_END. 
      SUBROUTINE FITPAR_END(IERR)
c
c User end-routine after all analysis/fits are done.
c [close files, summarize statistics, global analysis, etc ...]
c -------------------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


      INTEGER IERR ! (O) 0 => OK

c local var

      INTEGER LL

C ------------------- BEGIN ---------------------
      IERR = 0

      IF ( N_INTERP_MJDLIST .GT. 0 ) THEN
         CALL DMP_SNMJD_INTERP(-9,0)
      ENDIF

      IF ( OPT_COVAR_LCFIT > 0 ) THEN
        write(6,40) N_SNLC_COVFIX
 40     format(T8,'COV(mB,x1,c)-invertability fixed for ', I6,' events')
      ENDIF

      RETURN
      END

C ==========================================
CDECK  ID>,  FITPAR_PREP. 
      SUBROUTINE FITPAR_PREP ( iter, IERR )
c
c For each "isn" supernova, this user-routine is used to
c initialize global variables used as input to the fitter:
c
c NFITPAR             = number of fit parameters
c PARNAME_STORE(1:NFITPAR)  = name of each parameters (<= 10 bytes)
c INIVAL(1:NFITPAR)   = initial value
c INISTP(1:NFITPAR)   = initial step size (0 => fixed parameter!)
c
c
c Useful notes:
c
c
c It is highly recommened that the first fit parameter
c is INIVAL(1) = DBLE(ISN)  with INISTP(1) = 0.0
c You will need this index in FCNSNLC to get information
c about a particular SN.
c Another useful init is to set your initial MJD_AT_PEAK equal  to
c SNLC_SEARCH_PEAKMJD(isn) from Masao's LC fitter during the survey.
c
c
c Fill MAG_XTMW_REF(ifilt_obs)  so that  USRFUN
c can make the same approx MilkyWay correction that was
c applied to data.
c
c
c Mar 19 2024: set MASK_PHOTOZ_SOURCE
c
c ----------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &   iter  ! (I) fit iteration: 1,2, ... NFIT_ITERATION
     &  ,IERR  ! (O) 0=> init OK; else skip fit

c local var

      INTEGER
     &    NPAR, ipar
     &  , ifilt, ifilt_obs, ifilt_rest1, ifilt_rest2, ifilt_rest_iter1
     &  , istat, NUSE_FILT, OPT, LL, L2, LCHAR

      INTEGER i, cid, ipar1, ipar2, NPT, h1, h2  ! CONTOUR args

      REAL*8 LAMMIN,LAMMAX, LAMAVG, Z8, Z8TEST, GRAD(MXFITPAR)
      REAL*4 Z4, LMIN4

      CHARACTER CFILT*1, CCID*(MXCHAR_CCID), CTMP*8

      LOGICAL
     &   USE_FILT_ITER1(MXFILT_ALL)
     &  ,FIRST_ITER, NEXT_ITER, NOMATCH, LAMFAIL, LPRINT
     &  ,LPZ_HOST, LPZ_BEST, LPZ_Q, LZSPEC

c functions

      LOGICAL LFITFUN_FILT, FIRST_ITERATION, IS_ZSPEC
      INTEGER NEAREST_IFILTDEF_WRAPPER

      REAL*8   USRFUN
      EXTERNAL USRFUN

C ---------- BEGIN -------------

      IERR = 0  ! init to OK
      LPRINT = STDOUT_UPDATE

      FIRST_ITER = FIRST_ITERATION(ITER) .and. (.not. LREPEAT_ITER)

      NEXT_ITER  = ((.not. FIRST_ITER) .and. (ITER > 1))
     &            .or. LREPEAT_ITER

      if ( FIRST_ITER ) NEXT_ITER = .FALSE.

      IF ( FIRST_ITER .and. OPT_FILTER_UPDATE > 0 ) THEN

        IF ( LSED_FITMODEL ) CALL SEDMODEL_INI(1,IERR)

        IF ( LREST_FITMODEL ) THEN
          LL = INDEX(FITMODEL_VERSION,' ') - 1
          C1ERR = 'FILTER_UPDATE  option not implemented for ' //
     &              FITMODEL_VERSION(1:LL)
          C2ERR = '(rest-frame model) that uses K-corrections. Sorry.'
          CALL MADABORT("FITPAR_PREP", c1err, c2err)
        ENDIF

      ENDIF

c init Trest-related variables that are set after fit
      IF ( FIRST_ITER ) THEN
        TRESTMIN_FIT        = -999.
        TRESTMAX_FIT        = -999.
        TRESTRANGE_FIT      = -999.
        NFILT_TRESTMIN_FIT  = -9
        NFILT_TRESTMAX_FIT  = -9
        TGAPMAX_FIT         = -9.0
        T0GAPMAX_FIT        = -9.0

        CALL FITINI_EPVAR(-1)    ! added Jan 1, 2014
      ENDIF

      LBKSNINFO = .FALSE.

      NFITPAR_MN = IPAR_MAX  ! # MINUIT params includes NFIXPAR

      CCID  = SNLC_CCID
      LCHAR = ISNLC_LENCCID

c print global banner

      IF ( LPRINT ) THEN
        ctmp = ''
        if ( LREPEAT_ITER ) CTMP = '(again)'
        write(global_banner,400) ITER, CCID(1:LCHAR), CTMP
400     format('FITPAR_PREP: Begin FIT-ITERATION ', I2,
     &         ' for CID ', A, 3x, A )
        CALL PRBANNER( global_banner(1:68) )
      ENDIF

c load redshift to use in spec-z fit

      IF ( SNLC_ZHELIO < 0.0  .and. OPT_PHOTOZ == 0 ) then
         write(6,26) SNLC_CCID(1:LCHAR)
26       format(T5,'Z-WARNING for CID=',A,
     &      ' : no Z_helio => use ZCMB for lc fit' )
      ENDIF

c ------------------------------
c set global REDSHIFT_FIT to use for things like
c getting rest-frame filters and Trest values.

      CALL SET_REDSHIFT_FIT(iter)

      Z8 = DBLE(REDSHIFT_FIT)
      Z4 = REDSHIFT_FIT       ! ensure 4-byte redshift variable

c ---------------------------------
c set redshift-arg for LFITFUN_FILT (below)
c For photoz fit set Z8TEST=-9 so that z-dependent tests are
c skipped ; they are applied in PHOTOZ_ANA (after 1st fit) instead.

      Z8TEST = Z8
      IF ( DOFIT_PHOTOZ ) THEN
        Z8TEST = -9.0

c reset DROPFILTER array in first iteration only
        if ( FIRST_ITER ) then

c Mar 19 2024: set mask of which OPT_PHOTOZ option (bit) is actually used.
          MASK_PHOTOZ_SOURCE = 0

          LPZ_HOST = btest(OPT_PHOTOZ,BIT_PHOTOZ_GAUSS)
          LPZ_BEST = btest(OPT_PHOTOZ,BIT_BESTZ_GAUSS)
          LPZ_Q    = btest(OPT_PHOTOZ,BIT_PHOTOZ_QUANTILES)
          LZSPEC   = LPZ_BEST .and. IS_ZSPEC()
          if ( LPZ_Q .and. .not.LZSPEC )  THEN
             MASK_PHOTOZ_SOURCE =
     &          IBSET(MASK_PHOTOZ_SOURCE,BIT_PHOTOZ_QUANTILES)

cc xxxxxxxxxxxxx mark delete xxxxxxxxx
cc           METHOD_SPLINE_QUANTILES = "CUBIC" // char(0)
cc	     if (btest(OPT_PHOTOZ,BIT_PHOTOZ_QUANTILES_STEFFEN))  THEN
cc              METHOD_SPLINE_QUANTILES = "STEFFEN" // char(0)
cc            endif
cc xxxxxxxxxxxxx

          else if ( LPZ_BEST ) then
             MASK_PHOTOZ_SOURCE =
     &          IBSET(MASK_PHOTOZ_SOURCE,BIT_BESTZ_GAUSS)
          else if ( LPZ_HOST ) then
             MASK_PHOTOZ_SOURCE =
     &          IBSET(MASK_PHOTOZ_SOURCE,BIT_PHOTOZ_GAUSS)
          endif

          DO 220 ifilt_obs = 1,  MXFILT_ALL

            PHOTOZ_ADDFILTER(ifilt_obs)  = .FALSE.
            PHOTOZ_DROPFILTER(ifilt_obs) = .FALSE.

c skip initial DROP-FILTER test if cheat-flag is set
            IF ( DOFIT_PHOTOZ_CHEAT ) GOTO 220

c check option to exclude certain lambda regions on first
c iteration (default is to ignore UV filters).
c Note that any filters dropped here can get added back before
c 2nd iteration depending on the photoZ-fit value.

            LAMAVG  = FILTOBS_LAMAVG(ifilt_obs)
            LAMFAIL = LAMAVG .LT. PHOTOZ_ITER1_LAMRANGE(1)
     &          .or.  LAMAVG .GT. PHOTOZ_ITER1_LAMRANGE(2)

            if ( LAMFAIL ) then
              PHOTOZ_DROPFILTER(ifilt_obs) = .TRUE.
            endif

220         CONTINUE  ! end of IFILT_OBS
        endif  ! end if FIRST_ITER

      ENDIF  ! end of DOFIT_PHTOOZ

c ---------------------------------
c count how many filters to fit;
c a fit filter must:
c   -  be specified by the user (DOFIT_FILT)
c   -  exist in the lightcurve.
c   -  transform to rest-frame lambda within RESTLAMBDA_FITRANGE(2)
c

      NFILT_FIT         = 0
      FILTLIST_FIT_USE  = ''
      NFILT_OBS_USEFIT  = 0
      LAMMIN =  99999.
      LAMMAX = -99999.
      USE_FILT(0)  = .FALSE.       ! for protection against IFILT=0

c store USE_FILT array from previous iteration in order
c flag any changes in the 2nd iteration.

      if ( NEXT_ITER ) then
         DO ifilt     = 1, NFILTDEF_SURVEY
            ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
            USE_FILT_ITER1(ifilt_obs) = USE_FILT(ifilt_obs)
         ENDDO
      endif

      DO ifilt     = 1, NFILTDEF_SURVEY

         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt     = filtdef_string(ifilt_obs:ifilt_obs)

c set USE_FILT based on user-request, existence,
c and valid rest-frame filter.

         USE_FILT(ifilt_obs) =
     &      LFITFUN_FILT(ifilt_obs,Z8TEST)

         NOMATCH  =
     &     USE_FILT_ITER1(ifilt_obs) .NEQV. USE_FILT(ifilt_obs)

c print message if observer-filter is dropped or added on 2nd iteration
         if ( NEXT_ITER .and. NOMATCH .and. STDOUT_UPDATE ) THEN

             if ( USE_FILT_ITER1(ifilt_obs) ) then
                write(6,24) CCID(1:LCHAR), 'DROPPED', cfilt
             else
                write(6,24) CCID(1:LCHAR), 'ADDED', cfilt
             endif
24           format(T10,'WARNING for SN ',A,' : ',
     &            A,' obs-filter=', A )
         endif

         if ( USE_FILT(ifilt_obs) ) then

            NFILT_FIT = NFILT_FIT + 1
            MAG_XTMW_REF(ifilt_obs) = SNLC_MWXT_MAG(ifilt)

            LAMAVG = FILTOBS_LAMAVG(ifilt_obs)
            IF ( LAMAVG .LT. LAMMIN ) then
               LAMMIN = LAMAVG
            ENDIF

            IF ( LAMAVG .GT. LAMMAX ) then
               LAMMAX = LAMAVG
            ENDIF

            LL = INDEX ( FILTLIST_FIT_USE, ' ' ) - 1
            FILTLIST_FIT_USE = FILTLIST_FIT_USE(1:LL) // cfilt
            NFILT_OBS_USEFIT = NFILT_OBS_USEFIT + 1

            if ( LREST_FITMODEL ) then
              OPT = OPT_FILTOBS
              IFILT_REST_MAP(ifilt) =
     &         NEAREST_IFILTDEF_WRAPPER(OPT,ifilt_obs, 1, Z4, LMIN4)
            endif

         endif

      ENDDO

c set range of observer filters to evaluate for each obs filter.
c This is needed for the color transformation and for U -> U-BX+B

      CALL SET_IFILT_OBS(LPRINT)

      IF ( NFILT_FIT .EQ. 0 ) THEN
         print*,' '
         print*,' FITPAR_PREP WARNING for CID ', SNLC_CCID
         print*,'   Found no valid observer frame filters to fit.'
         print*,'   '
         IERR = ERRFLAG_FITPREP_NOFILTERS
         RETURN
      ENDIF

c init EP_XXX arrays ( before calling FITINI_ADJUST)
      CALL FITINI_EPVAR(iter)

c set INIVAL and INISTP arrays.
      CALL FITINI_PARVAL(iter)

c init linear FITCOV arrays
      OPT = 1  ! bit 1 => print info to stdout
      CALL FITINI_COV(OPT, ITER, FITVAL(1,ITER-1), IERR)
      IF ( IERR .NE. 0 ) RETURN

c check for photoZ fit (after FITINI_COV)
      IF ( DOFIT_PHOTOZ ) CALL FITINI_PHOTOZ(iter)

c adjust fitpar based on initial Fdata/Fmodel ratios.
      CALL FITINI_ADJUST(iter)

c Apr 29 2022: check 1st iter override from SNCID_LIST_FILE
      CALL FITINI_LIST_FILE(iter)

      IF ( LREST_FITMODEL .and. ITER .EQ. NFIT_ITERATION ) THEN
        CALL FITINI_PRKCOR()   ! print Kcor info
      ENDIF

c check option to fix all parameters in fit

      IF ( LFIXPAR_ALL .or. LFIXPAR_ADJUST ) THEN
        DO ipar = 1, NFITPAR_MN
           INISTP(ipar)  = 0.0
        ENDDO
      ENDIF

c Check for contour plots with namelist array CONTOUR_LIST
c Contour plots are initialized for each SN before MINUIT is run.

      IF ( ITER .EQ. NFIT_ITERATION ) THEN
        DO i = 1, 20
           CID   = CONTOUR_LIST(1,i)
           ipar1 = CONTOUR_LIST(2,i)
           ipar2 = CONTOUR_LIST(3,i)
           NPT   = CONTOUR_LIST(4,i)

           h1 = 20000 + i*10  ! histograms go into subdir for each SN
           h2 = h1 + 1
           if ( CID .EQ. SNLC_CID ) then
              CALL BOOK_CONTOUR(h1,h2, NPT, IPAR1, IPAR2 )
           endif
        END DO

      ENDIF

c ---------------
      CALL FLUSH(6)

      RETURN
      END   ! end of FITPAR_PREP


C =====================================
CDECK  ID>,  FITINI_EPVAR. 
      SUBROUTINE FITINI_EPVAR(ITER)
      IMPLICIT NONE

c init R4 and I4 arrays

      INTEGER ITER  ! (I) SN index and iteraion

c local var


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )


cc +CDE,SNDATCOM.
cc +CDE,SNLCINP.

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER  epoch, ifilt, i, ep, ivar

c ----------- BEGIN -------------

      IF ( ITER < 0 ) THEN
         DO ep = 1, MXFIT_DATA

            DO ivar = 1, MXVAR_R4
               R4EP_ALL(ep,ivar)  = NULLVAL
               R4EP_FIT(ep,ivar)  = NULLVAL
               R4EP_LAST(ep,ivar) = NULLVAL
            ENDDO
            DO ivar = 1, MXVAR_I4
               I4EP_ALL(ep,ivar) = -999
               I4EP_FIT(ep,ivar) = -999
            ENDDO
            BANDEP_ALL(ep) = ''
            BANDEP_FIT(ep) = ''
         ENDDO
      ENDIF


c init scalars
      R4SN_TEARLY       = +999
      R4SN_TLATE        = -999.
      R4SN_MJDmin       = +6E8
      R4SN_MJDmax       = -6E8
      R4SN_FFSUM_DATA   = NULLVAL
      R4SN_FFSUM_MODEL  = NULLVAL
      R4SN_FFSUM_CROSS  = NULLVAL
      R4SN_FFSUM_WGT    = NULLVAL
      R4SN_FFSUM_RATIO  = NULLVAL

c init filter-dependent variables.

      DO ifilt = 1, MXFILT_ALL
           PEAKMAG_OBS_MODEL(ifilt)           = NULLVAL
           PEAKMAG_OBS_MODEL_ERR(ifilt)       = 0.0
           PEAKMAG_REST_MODEL(ifilt)          = NULLVAL
           PEAKMAG_REST_MODEL_ERR(ifilt)      = 0.0
           PEAKFLUX_OBS_MODEL(ifilt)          = NULLVAL
           PEAKFLUX_OBS_MODEL_ERR(ifilt)      = 0.0
           PEAKFLUX_OBS_MODEL_COR(ifilt)      = 1.
           PEAK_KCOR_MODEL(ifilt)             = 0.0

           R4BAND_SNRMAX_FIT(ifilt)     = -99.
           R4BAND_SNRMAX_RAW(ifilt)     = NULLVAL
           R4BAND_TREST_NEARPEAK(ifilt) = -999.
           R4BAND_XTMW_NEARPEAK(ifilt)  = NULLVAL

           if ( ifilt .LE. MXFILT_OBS ) then
              FCN_FITCHI2(ifilt)    = 0.0
           endif
      ENDDO

      RETURN
      END     ! end of FITINI_EPVAR


C ===================================================
CDECK  ID>,  FITPAR_ANA. 
      SUBROUTINE FITPAR_ANA ( isn, iter, ERRFLAG )
c
c User-routine to analyze fit results after each SN.
c Includes incrementing histograms, statistics, etc ...
c
c Fit results are in
c
c   FITPAR(1:NFITPAR)
c   FITERR(1:NFITERR)
c
c Recommend making (REAL*8) equivalence to local
c variables with more appropriate names.
c
c Returns ERRFLAG as follows:
c  =  0 => OK; keep SN
c  = >0 => discard fit (call CDTOPDIR)
c  = -1 => decrement ITER and try again (e.g., for photoZ spike)
c
c
c
c Oct 26 2015: remove obsolete ISN arg from FITANA_STORE.
c
c Jan 04 2016: if MNSTAT_COV<3 (bad cov matric), set ERRFLAG=-1
c              to fit again
c
c July 27 2017: for photo-z fit, set SNLD_zHD=zPHOT
c
c Oct 24 2017:
c   move MAKEDIR_OUTPUT() call down inside DOLC_PLOT if-block.
c   Pass FALSE DOPLOT-flag to FITANA_MARGE since the subDir
c   no longer exists when FITANA_MARG is called.
c   This fixes problem of having empty subDir for each
c   SN that passes SNANA cuts but fails FIT cuts.
c
c Jun 21 2018:
c   check CRAZYFITERR on every iteration to check for NaN
c
c Feb 28 2020:
c   set ERRFLAG = -1 (repeat iter) if both ITER1_MAXFRAC and
c   DELCHI2_REJECT are set. Fixes long-standing bug.
c
c Aug 28 2020: if ERRFLAG=0 then set CUTFLAG_SNANA += 2 so that
c              correct CUTFLAG_SNANA shows up in FITRES table.
c
c May 18 2021: skip crazyflux check of OPT_SNCID_LIST > 0
c
c --------------------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


C +CDE,VMAXCOM. inserted below by ypatchy. 

c Created Jun 2013 by R.K.

c Examples for OPT_VMAX
c  OPT_VMAX = 2 -> use obs for mag, peak for Zmax
c  OPT_VMAX = 3 -> use peak for both mag and Zmax


      INTEGER
     &  MXFILT_VMAX
     & ,OPTBIT_MAG    ! Zmax at epoch of max obs brightness
     & ,OPTBIT_ZMAX
     & ,OPTBIT_VERBOSE

      REAL*8  MAGDIF_CONVERGE

      PARAMETER (
     &   MXFILT_VMAX   = 5
     &  ,OPTBIT_MAG    = 0  ! bit0 off/on -> mag at best-fit obs/peak
     &  ,OPTBIT_ZMAX   = 1  ! bit1 off/on -> zmax from best-fot obs/peak
     &  ,OPTBIT_VERBOSE = 7 ! bit7(128) -> verbose printout
     &  ,MAGDIF_CONVERGE = 0.001 ! stop when |mag(zmax)-MAGLIM| < CONVERGE
     &     )

      INTEGER
     &   NFILT_VMAX   !Number of obs filters to compute Zmax/Vmax
     &  ,IFILTOBS_LIST_VMAX(MXFILT_VMAX) ! sparse list

      REAL
     &   MAGLIM_LIST_VMAX(MXFILT_VMAX)
     &  ,TREST_LIST_VMAX(MXFILT_VMAX)
     &  ,MAG_LIST_VMAX(MXFILT_VMAX)
     &  ,Z_LIST_VMAX(MXFILT_VMAX)
     &  ,VOL_LIST_VMAX(MXFILT_VMAX)

      INTEGER NEP_LIST_VMAX(MXFILT_VMAX)

      CHARACTER FILTLIST_VMAX*20

      COMMON/ VMAXCOM /
     &    NFILT_VMAX, IFILTOBS_LIST_VMAX
     &   ,FILTLIST_VMAX, MAGLIM_LIST_VMAX
     &   ,TREST_LIST_VMAX, MAG_LIST_VMAX, Z_LIST_VMAX, VOL_LIST_VMAX
     &   ,NEP_LIST_VMAX

C ===================================

      INTEGER
     &   isn   ! (I) sparse SN index
     &  ,iter  ! (I) fit iteration: 1,2, ... NFIT_ITERATION
     &  ,ERRFLAG  ! (O)

c local var

      INTEGER
     &   IFILT, IFILT_OBS, CID, LCID, IERR, NFIT_PLOT
     &  ,OPT, hid, i, IERR_MARG

      LOGICAL DOLC_PLOT, LFITOK,  FIRST, LAST, DO_REFIT
      LOGICAL LMAXFRAC, LCHI2REJ, CRAZY
      REAL FRACERRDIF
      character sdir*20, chis*40, ccid*(MXCHAR_CCID)

c function
      LOGICAL CRAZYFITERR, DOPLOT_SNLC

C -------------------- BEGIN ---------------

      ERRFLAG  = 0   ! init output to "accept"
      LAST     = ITER .EQ. NFIT_ITERATION
      FIRST    = ITER .EQ. 1

      CID   = SNLC_CID
      CCID  = SNLC_CCID
      LCID  = ISNLC_LENCCID

c transfer I4/R4EP_ALL arrays to sparse I4/R4EP_FIT arrays (Jan 25 2014)
      CALL LOAD_EPFIT()

c for photoz fit, check for repeat iteration or discard fit
      IF ( DOFIT_PHOTOZ ) THEN
         CALL PHOTOZ_ANA(1,iter,ERRFLAG)
         IF ( LAST ) THEN
            CALL SET_ZHD_PHOTOZ()
            IF ( ERRFLAG > 0 ) RETURN
         ENDIF
      ENDIF

c --------------------------------------------
c Jan 2016: fit iteration again if cov matrix has not converged

      DO_REFIT =
     &     OPT_MNSTAT_COV > 0 .and.  ! user option
     &     LAST               .and.  ! last fit iteration
     &     MNSTAT_COV < 3     .and.  ! MINUIT status
     &     (.not. LREPEAT_ITER)      ! not already repeating

      IF ( DO_REFIT ) THEN
         write(6,46) MNSTAT_COV, CCID
46       format(T5,'Bad COV matrix (MNSTAT_COV=',I2,') '
     &              '-> repeat fit for CID=',A12 )
         ERRFLAG = ERRFLAG_REPEAT_ITER  ! -1
         RETURN
      ENDIF

c --------------------------------------------
c May 2018 check option to repeat entire fit with MINOS

      FRACERRDIF = LCFRACERRDIF_STORE(IPAR_COLOR)
      DO_REFIT =
     &    LAST                  .and.  ! last fit iteration
     &    (.NOT. LREPEAT_MINOS) .and.
     &    ABS(FRACERRDIF) > FRACERRDIF_REPEATFIT  ! large cERR change
     &
      IF ( DO_REFIT ) THEN
         write(6,48) FRACERRDIF, CCID(1:12)
 48      format(T5,'Unstable c-error: cFRACERRDIF=',F6.2,
     &              '-> repeat fit with MINOS, CID=',A12 )
         ERRFLAG = ERRFLAG_REPEAT_MINOS  ! -2
         RETURN
      ENDIF

c set default of NFIT=1 to plot (before calling FITRESTMAG or FITMAGDIF)
c This call is not needed, but avoids confusion with NFIT=0 inside the
c sntools_output routines.
      IF ( ITER .EQ. 1 ) THEN
        CALL SNLCPAK_NFIT(1)   ! 5/01/2014
      ENDIF

c check optional rest-mag  (Feb 2012)
      CALL FITRESTMAG_CALC(ITER)

c check optional magdif test (Mar 2013)
      CALL FITMAGDIF_CALC(ITER)

c check optional IDEAL fit with FLUX=TRUEFLUX (Aug 2017)
      CALL SIMFIT_IDEAL_CALC(ITER)


c -------------------------------------------------
c check for crazy errors, unless:
c   + plotchi2-debugger is on, or
c   + OPT_SNCID_LIST is set

      CRAZY = CRAZYFITERR(isn,iter) .and.
     &    (.not. LPLOTCHI2 .and. OPT_SNCID_LIST==0)

      IF ( CRAZY ) THEN
        write(6,222) CCID(1:LCID)
222     format(T15,'CRAZY ERROR for CID=', A,' ==> SKIP ' )
        ERRFLAG = ERRFLAG_FIT_CRAZYERR
        RETURN
      ENDIF

c ---------------------------------------
      IF ( ITER < NFIT_ITERATION ) RETURN

c ----- BELOW IS LAST ITERATION -------

c check for special variable computation for SIMSED models;
      CALL SIMSED_RECON()

c ------------------------------------------------------
c compute SIMCHI2 on last iteration
cc      IF ( LSIM_SNANA .and. LAST ) then
cc 4.22.2019: disable because of problem with wrong host redshift
cc         CALL GET_SIMCHI2_CHEAT()
cc      ENDIF

c -------------------------------------------------
      DOLC_PLOT = DOPLOT_SNLC()

c ---------------------------------------
c check option to marginalize

      if ( LTRACE ) CALL DMPTRACE("CALLING FITANA_MARG")

      CALL FITANA_MARG(ISN, .FALSE., IERR_MARG)
      IF ( IERR_MARG > 0 ) THEN
         ERRFLAG = ERRFLAG_FIT_MARGINALIZE
         GOTO 333
         RETURN          ! discard fit
      ENDIF

c ---------------------------------------
c store fit results for plotting

      if ( LTRACE ) CALL DMPTRACE("CALLING FITANA_STORE")

      CALL FITANA_STORE()

c ---------------------------------------
c Use fitted flux to update ERROR CALC from ZPT,PSF and SKY

      if ( LTRACE ) CALL DMPTRACE("CALLING UPD_FLUXERRCALC")
      CALL UPD_FLUXERRCALC()

c -------------------------------
c Nov 2018: Check option to fix non-invertible COV(mB,x1,c)
      CALL FIX_COVAR_LCFIT()

c ----------------------
c check option to compute Zmax for 1/Vmax method
c (after FITANA_STORE ad before SNTABLE calls)
      do i = 1, NFILT_VMAX
         CALL VMAX_ANA(i)
      enddo

c ----------------------------------------
c on last iteration, check if fit is OK

      if ( LTRACE ) CALL DMPTRACE("CALLING FITANA_CUTS")
      CALL FITANA_CUTS(isn,LFITOK)    ! returns LFITOK
      IF ( .NOT. LFITOK ) THEN
         ERRFLAG = ERRFLAG_FIT_CUTS
         GOTO 333
      ENDIF

      if ( LTRACE ) CALL DMPTRACE("CALLING FITANA_SUMMARY")

      CALL FITANA_SUMMARY(isn)

 333  CONTINUE

      IF ( ERRFLAG .NE. 0 ) THEN
c back to topdir
          CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)
          RETURN
      ENDIF

c - - - - - - -
c Aug 28 2020: if we get here, set CUTFLAG_SNANA bit for fit success.
      CUTFLAG_SNANA  = IBSET(CUTFLAG_SNANA,1) ! for SNANA tree

c ---------------------------------------------------------
c book plots for this SN; all plots are vs. relative epoch

      IF ( DOLC_PLOT ) THEN

         CCID = SNLC_CCID(1:LCID) // char(0)
         CALL MAKEDIR_OUTPUT(CCID,SNLC_CID,LCID)

        if ( LTRACE ) CALL DMPTRACE("inside DOLC_PLOT if-block")

        CALL SNLCPLOT()

        IF ( LPLOTCHI2 ) CALL HFUNMIN()    ! plot fun near minium

        CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! back to topdir

      ENDIF

c ---------------------------------
c check for NN-analysis (Apr 2014) after CDTOPDIR_OUTPUT
      IF ( NVAR_NEARNBR > 0 ) CALL FITPAR_NEARNBR_APPLY()

c check tables to fill
      IF ( OPT_TABLE(ITABLE_FITRES) > 0 ) THEN
          CALL PREP_FITRES_TABLEVAR()
          CALL TABLE_SNFIT(IDTABLE_FITRES,IFLAG_ANA)
      ENDIF

      IF ( OPT_TABLE(ITABLE_MODELSPEC) > 0 .and.
     &     FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
         CALL TABLE_SNSPEC_SALT2(isn)
      ENDIF


      IF ( SALT2_DICTFILE .NE. ' ' ) THEN
         CALL DMP_DICTFILE(1)
      ENDIF

c check for single-epoch dump of FLUX & MAG at specified MJD
c See input namelist "SNMJD_LIST_FILE"

      IF ( N_INTERP_MJDLIST > 0 ) THEN
        CALL DMP_SNMJD_INTERP(1,1)  ! evaluate at MJD from LIST file
        CALL DMP_SNMJD_INTERP(1,0)  ! evaluate at PEAK
      ENDIF

      RETURN
      END      ! end of FITPAR_ANA

C ================================================
CDECK  ID>,  CRAZYFITERR. 
      LOGICAL FUNCTION CRAZYFITERR(isn,iter)

c Returns TRUE if a crazy fit error is identified.
c Jan 28 2020: check for crazy-small errors too, only if floated.

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER ISN, ITER ! (I) ! SN index & fit-iteration
      REAL ERR_COLOR, ERR_SHAPE, ERR_DIST, ERR_PKMJD
      LOGICAL LNAN, FLOAT_COLOR, FLOAT_SHAPE, FLOAT_DIST, FLOAT_PKMJD

C --------------- BEGIN ----------------

      CRAZYFITERR = .FALSE.

      ERR_COLOR =  FITERR(IPAR_COLOR,ITER)
      ERR_SHAPE =  FITERR(IPAR_SHAPE,ITER)
      ERR_DIST  =  FITERR(IPAR_DLMAG,ITER)
      ERR_PKMJD =  FITERR(IPAR_PEAKMJD,ITER)

      FLOAT_COLOR = FLOATPAR(IPAR_COLOR)
      FLOAT_SHAPE = FLOATPAR(IPAR_SHAPE)
      FLOAT_DIST  = FLOATPAR(IPAR_DLMAG)
      FLOAT_PKMJD = FLOATPAR(IPAR_PEAKMJD)

c xxxxxxxxxxxxxxxxxxx
c      print*, ' xxx '
c      print*, ' xxx -------- CRAZYFITERR iter=', iter
c      print*, ' xxx ERR(c,s,d,t0) = ',
c     &     ERR_COLOR, ERR_SHAPE, ERR_DIST, ERR_PKMJD
c xxxxxxxxxxxxxxxxxxx

c if we are fitting only 1 filter, then don't bother
c checking crazy error

      if ( .NOT. CHECK_CRAZYFITERR ) then
         RETURN
      endif

c check for NaN on every fit iteration
      LNAN = .FALSE.
      if ( ISNAN(ERR_COLOR) ) LNAN = .TRUE.
      if ( ISNAN(ERR_SHAPE) ) LNAN = .TRUE.
      if ( ISNAN(ERR_DIST)  ) LNAN = .TRUE.
      if ( ISNAN(ERR_PKMJD) ) LNAN = .TRUE.

      IF ( LNAN ) THEN
         CRAZYFITERR = .TRUE.
         RETURN
      ENDIF

c don't do any more until last iteration
      IF ( ITER < NFIT_ITERATION ) THEN
         RETURN
      ENDIF

c ------------------------
c last fit iteration

      CRAZYFITERR = .TRUE.
      IF ( FLOAT_COLOR ) THEN
        IF ( ERR_COLOR > 3.0  .or. ERR_COLOR < 1.0E-8  ) RETURN
      ENDIF

      IF ( FLOAT_SHAPE ) THEN
        IF ( ERR_SHAPE > 3.0  .or. ERR_SHAPE < 1.0E-8  ) RETURN
      ENDIF

      IF ( FLOAT_DIST ) THEN
        IF ( ERR_DIST  > 3.0  .or. ERR_DIST  < 1.0E-15 ) RETURN
      ENDIF

      IF ( FLOAT_PKMJD ) THEN
        IF ( ERR_PKMJD > 10.0 .or. ERR_PKMJD < 1.0E-8  ) RETURN
      ENDIF

      CRAZYFITERR = .FALSE.

      RETURN
      END   ! end CRAZYFITERR

C =====================================
CDECK  ID>,  FIRST_ITERATION. 
      LOGICAL FUNCTION FIRST_ITERATION(ITER)

C Created Aug 2017
C Return TRUE on first iteration of fit.
C Normally this is when ITER=1, but with some exceptions
C involving mutliple/repeat fits

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


      INTEGER ITER
C ---------------- BEGIN ---------------

      FIRST_ITERATION = (ITER .EQ. 1) ! .and. (.not. LREPEAT_ITER)

      IF ( DOFIT_IDEAL_EVENT .and. ITER.EQ.NFIT_ITERATION_IDEAL+1) then
         FIRST_ITERATION = .TRUE.
      ENDIF

      RETURN
      END    ! end  FIRST_ITERATION


C ===============================
CDECK  ID>,  SIMSED_RECON. 
      SUBROUTINE SIMSED_RECON()

c Created Jun 28, 2012
c If SIMSED model has parameters S2c and S2x1,
c compute SIMMB and SIMx0.
c Beware that ALPHA and BETA are hard-wired.
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )



      INTEGER IPAR, IPARx1, IPARc
      REAL S2x1, S2c, S2x0, S2x0inv, arg

C --------------- BEGIN ------------

      IF ( .NOT. LSIM_SNANA   ) RETURN
      IF ( NPAR_SIMSED .LE. 0 ) RETURN

c for SIMSED model with S2x1 and S2c,
c compute SIM_SALT2mb and SIM_SALT2x0

      IPARx1 = -9
      IPARc  = -9
      DO 100 ipar = 1, NPAR_SIMSED
        if ( SIMSED_PARNAME(IPAR)(1:4) .EQ. 'S2x1' ) then
            IPARx1 = IPAR
        endif
        if ( SIMSED_PARNAME(IPAR)(1:3) .EQ. 'S2c' ) then
            IPARc = IPAR
        endif
100   CONTINUE

      IF ( IPARx1 .GT. 0 .and. IPARc .GT. 0 ) THEN
         S2c  = SIMSED_PARVAL(IPARc)
         S2x1 = SIMSED_PARVAL(IPARx1)
         arg       = ( SIM_DLMAG - SALT2alpha*S2x1 + SALT2beta*S2c ) ;
         S2x0inv   = 1.0E-12 * (10.0**(0.4*arg) )
         S2x0      = 1./S2x0inv ;
         SIM_SALT2mB = 10.635 - 2.5*log10(S2x0);
         SIM_SALT2x0 = S2x0
      ENDIF

      RETURN
      END

C ======================================
CDECK  ID>,  FIX_COVAR_LCFIT. 
      SUBROUTINE FIX_COVAR_LCFIT()

c Nov 2018
c Check option to fix COV(mB,x1,c) if not invertible.
c Use algorithm for Marriner 2011 (SALT2mu code),
c which is update_covMatrix() function in sntools.c
c
c Uses &FITINP OPT_COVAR_LCFIT mask, with mask options
c defined below as parameters.
c
c There are two options here to fix COV to ensure invertibility:
c 1. M11 (Marriner 2011):
c    Diagonal COV is ERROR^2, and off-diag is from Minuit's MNEMAT
c    Beware that MNEMAT diagonals correpond to parabolic error,
c    not MINOS error.
c
c 2. RED: use reduced covariance from MNEMAT and MINOS errors to
c    to construct COV matrix.
c
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c +CDE,SNLCINP.

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER
     &   OPTMASK_COVAR_FIXCOV_M11  ! fix non-invertible COV as in Marriner11
     &  ,OPTMASK_COVAR_FIXCOV_RED  ! fix COV using reduced FITERRMAT
     &  ,OPTMASK_COVAR_DUMPROW     ! one-row dump for each fix
     &  ,OPTMASK_COVAR_DUMPFULL    ! dump COV(old) -> COV(fix)
      PARAMETER (
     &   OPTMASK_COVAR_FIXCOV_M11 =   1
     &  ,OPTMASK_COVAR_FIXCOV_RED =   2
     &  ,OPTMASK_COVAR_DUMPROW    = 128
     &  ,OPTMASK_COVAR_DUMPFULL   = 256
     &     )

      CHARACTER NAME*20
      LOGICAL  L_VALID, L_UPD
      INTEGER  FIXCOV_M11, FIXCOV_RED, LDMP1, LDMP2
      INTEGER  OPT, OPTMASK, IPAR, IPAR2, NPAR, IERR, LENCCID, i,j
      INTEGER  IPAR_LIST(10)
      REAL*8   COV_ORIG(3,3), COV_UPD(3,3), X0JACOB(3,3)
      REAL*8   MBERR, X0, X0ERR, COV_TMP, ERR_TMP, ERR2_TMP,SF,EIGMIN
      REAL*8   COV_MN, COR_MN
      EXTERNAL UPDATE_COVMATRIX

C -------------- BEGIN --------------

      IF ( OPT_COVAR_LCFIT == 0 ) RETURN

      OPT = OPT_COVAR_LCFIT
      FIXCOV_M11 = IAND ( OPT, OPTMASK_COVAR_FIXCOV_M11 )
      FIXCOV_RED = IAND ( OPT, OPTMASK_COVAR_FIXCOV_RED )
      LDMP1      = IAND ( OPT, OPTMASK_COVAR_DUMPROW    )
      LDMP2      = IAND ( OPT, OPTMASK_COVAR_DUMPFULL   )

      L_VALID = .FALSE.
      if ( FIXCOV_M11 > 0 ) L_VALID = .TRUE.
      if ( FIXCOV_RED > 0 ) L_VALID = .TRUE.

      if ( .NOT. L_VALID ) then
         write(C1ERR,66) OPT_COVAR_LCFIT
 66      format('Invalid &FITINP  OPT_COVAR_LCFIT = ', I8 )
         C2ERR = 'Check bit-options in subroutine FIX_COVAR_LCFIT'
         CALL MADABORT("FIX_COVAR_LCFIT", C1ERR, C2ERR)
      endif

c load list of fit-param IPAR used to construct local COV
      NPAR = 3
      IPAR_LIST(1) = IPAR_X0
      IPAR_LIST(2) = IPAR_SHAPE
      IPAR_LIST(3) = IPAR_COLOR

c define jacobian factor for x0err
      X0    = LCVAL_STORE(IPAR_X0)
      SF    = -2.5/(x0*LOGTEN)

c set diagonal COV using stored errors ; don't use diagonal FITERRMAT
c since it's not necessarily ERR^2.

      DO i = 1, NPAR
         IPAR    = IPAR_LIST(i)
         ERR_TMP = LCERR_STORE(IPAR)
         do j = 1, NPAR
            IPAR2 = IPAR_LIST(j)
            ERR2_TMP = LCERR_STORE(IPAR2)
            X0JACOB(i,j) = 1.0
            COV_MN       = FITERRMAT(IPAR,IPAR2) ! minuit COV
            COR_MN       = FITCORMAT(IPAR,IPAR2) ! minuit reduced corr
            if ( IPAR  == IPAR_X0 ) X0JACOB(i,j) = X0JACOB(i,j)*SF
            if ( IPAR2 == IPAR_X0 ) X0JACOB(i,j) = X0JACOB(i,j)*SF

            if ( i == j ) then
               COV_ORIG(i,i) = (ERR_TMP * ERR_TMP)
            else
               if ( FIXCOV_M11 > 0 ) then
                  COV_ORIG(i,j) = COV_MN
               else
                  COV_ORIG(i,j) = (ERR_TMP*ERR2_TMP) * COR_MN
               endif
            endif
            COV_ORIG(i,j) = COV_ORIG(i,j)*X0JACOB(i,j)
            COV_UPD(i,j)  = COV_ORIG(i,j)
         enddo
      ENDDO


c ----------------------------------
c prepare arguments for update_covmatrix

      LENCCID = INDEX(SNLC_CCID,' ') - 1
      NAME    = SNLC_CCID(1:LENCCID) // char(0)
      OPTMASK = 0
      if ( LDMP2>0 ) OPTMASK = 4   ! 1=abort on bad COV,  4=dump
      EIGMIN  = 0.0001

cc      print*,' xxx LDMP(1,2) = ', LDMP1, LDMP2, OPTMASK

      call update_covmatrix(NAME, OPTMASK, NPAR, COV_UPD, EIGMIN,
     &           IERR, LENCCID)

      L_UPD = ( (IERR .NE. 0) .or. FIXCOV_RED>0 )
      if ( L_UPD ) then
         N_SNLC_COVFIX = N_SNLC_COVFIX + 1

         DO i = 1, 3
            IPAR = IPAR_LIST(i)

            DO j = 1, 3
               IPAR2 = IPAR_LIST(j)
               COV_TMP = COV_UPD(i,j)
               if ( i == j ) then
                  LCERR_STORE(IPAR) = sqrt(COV_TMP/X0JACOB(i,i))
               else
                  FITERRMAT(IPAR,IPAR2) = COV_TMP/X0JACOB(i,j)
               endif
            ENDDO
         ENDDO

c update MBERR based on updated x0ERR
         X0ERR = LCERR_STORE(IPAR_X0)
         MBERR = X0ERR * abs(SF)
         LCERR_STORE(IPAR_MB) = MBERR
      ENDIF

c --- check dump options ----

      if ( LDMP1>0 .and. L_UPD ) then
         write(6,20) SNLC_CCID(1:12)
 20      format(T8,'Fix COV(mB,x1,c) for CID ', A)
      endif

      RETURN
      END

C ======================================
CDECK  ID>,  UPDECALC. 
      SUBROUTINE UPD_FLUXERRCALC()

c Feb 24, 2012
c Loop over fitted epochs and call FLUXERRCALC
c with fitted flux rather than the FLUXCAL from
c the data file.
c
c Nov 27, 2012: remove ISN argument from subroutine and from
c                FLUXERRCALC call.
c
c -------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



c +CDE,SNANAFIT.
c +CDE,SNLCINP.

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFITDATA, iep, imjd, ifilt
      REAL    FLUXCAL, FLUXCAL_ERR

C -------------- BEGIN -------------

      IF ( .NOT. DO_FLUXERRCALC ) RETURN

      DO 200 ifitdata  = 1, NFITDATA
         iep           = EPLIST_FIT(ifitdata)
         FLUXCAL       = R4EP_ALL(iep,JEP_MODELFLUX)
         FLUXCAL_ERR   = R4EP_ALL(iep,JEP_DATAFLUX_ERR)
         CALL FLUXERRCALC(iep, FLUXCAL, FLUXCAL_ERR)

200   CONTINUE
      RETURN
      END

C ==================================
CDECK  ID>,  SETCUTTR. 
      SUBROUTINE SETCUTS_FITWIN_TREST

c Jan 2012
c By default set each FITWIN_TREST_FILT = global FITWIN_TREST
c Then check user-namelist strings FITWIN_TREST_FILTER
c for tighter TREST-windows.
c
c Initial use is to limit the SNACC-filter Trest-range
c because the FUDGE_FITERR options allow downweighting
c but not removing epochs. The FITWIN_TREST_FILTER option
c allow removing epochs in specific filters.
c
c May 26, 2012:
c  fix aweful bug. First do-loop to init FITWIN_TREST_FILT
c  is now up to MXFILT_ALL=80 instead of MXFILT_OBS=62.
c  Previously FITWIN_TREST_FILT with IFILT_OBS > 62 were
c  not initialized, and thus these filters were likely
c  dropped on 2nd fit iteration.
c
c ------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER ifilt_obs, iwd, NWD, NFILT, ifilt, LEN, MSKOPT
      REAL    TMIN, TMAX
      CHARACTER CFILT*(MXFILT_ALL), CFILT1*2, CWD*60, FNAM*24

c function
      INTEGER FILTINDX

      INTEGER  STORE_PARSE_WORDS
      EXTERNAL STORE_PARSE_WORDS

C ------------ BEGIN -----------

      FNAM = 'SETCUTS_FITWIN_TREST'

c first set each filter-Trest window to the global default.
ccc   DO ifilt_obs = 1, MXFILT_OBS !!! aweful bug fixed May 2012
      DO ifilt_obs = 1, MXFILT_ALL
        FITWIN_TREST_FILT(1,ifilt_obs) = FITWIN_TREST(1)
        FITWIN_TREST_FILT(2,ifilt_obs) = FITWIN_TREST(2)
      ENDDO

c count how many FITWIN_TREST_FILTER cuts have been  specified.
      IF ( FITWIN_TREST_FILTER .EQ. ' ' ) RETURN

      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      NWD = STORE_PARSE_WORDS(MSKOPT, FITWIN_TREST_FILTER//char(0),
     &    FNAM//char(0), 80, 24)

c make sure that number of elements is a multiple of
c three (filters, TMIN, TMAX)

      IF ( mod(NWD,3) .NE. 0 ) then
        C1ERR = 'Invalid FITWIN_TREST_FILTER = '
        C2ERR = FITWIN_TREST_FILTER
        CALL MADABORT("SETCUTS_FITWIN_TREST", C1ERR, C2ERR)
      ENDIF

      DO 100 iwd  = 1, NWD, 3

        CALL get_PARSE_WORD_fortran(iwd+0, CWD, LEN)
        CFILT = CWD

        CALL get_PARSE_WORD_fortran(iwd+1, CWD, LEN)
        read(CWD,*) TMIN
        CALL get_PARSE_WORD_fortran(iwd+2, CWD, LEN)
        read(CWD,*) TMAX

        NFILT = INDEX(CFILT,' ') - 1
        do ifilt = 1, NFILT
           cfilt1 = CFILT(ifilt:ifilt)
           ifilt_obs = FILTINDX(cfilt1)
           FITWIN_TREST_FILT(1,ifilt_obs) = TMIN
           FITWIN_TREST_FILT(2,ifilt_obs) = TMAX
           write(6,20) CFILT1, TMIN, TMAX
20         format(T5,'Set special FITWIN_TREST(filt=',A1,') : ',
     &              F6.1,' to ', F6.1)
        enddo

100   CONTINUE

      CALL FLUSH(6)

      RETURN
      END

C ===================================================
CDECK  ID>,  SEDMODINI. 
      SUBROUTINE SEDMODEL_INI(IFLAG,IERR)
c
c Created Nov 09, 2010 by R.Kessler
c
c Called from FITPAR_INI to initialize model(s) based
c on a SED spectral surface. This init includes
c primary reference, filters, and the model-dependent
c INIT_GENMAG_XXX() function.
c
c Models supported:
c  - SALT2
c  - SIMSED
c
c
c  IFLAG = 0 => called before any SN have been fitted (init stage)
c  IFLAG > 0 => called just before fitting each SN
c
c    HISTORY
c
c Jun 24 2018: pass NONE argument to INIT_GENMAG_SALT2
c
c Jul 09 2019: call set_UVLAM_EXTRAPFLUX_SEDMODEL
c
c Apr 20 2020: fix dimenstion of TMP_FITMODEL to allow paths
c
c ---------------------------------------------------------

      IMPLICIT NONE

c subroutine args
      INTEGER  IFLAG   ! (I) 0-> one-time init
      INTEGER  IERR    ! (O) 0 => OK

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FILTUPDCM. inserted below by ypatchy. 

c Nov 2010
c information related to updating filter transmissions for each SN
c

      INTEGER
     &  OPT_FILTER_UPDATE   ! global flag for filter update
     & ,DOFLAG_FILTER_UPDATE(MXFILT_ALL)  ! track which filters to update

      CHARACTER
     &  FILTER_UPDATE_TOPDIR*(MXCHAR_FILENAME)  !full path to filt-trans files

      COMMON / FILTUPDCOM /
     &   OPT_FILTER_UPDATE, DOFLAG_FILTER_UPDATE, FILTER_UPDATE_TOPDIR

c ------------------------------------

c define updated filt-tran for SN and REF;
c the FILTOBS_TRANS arrays change for each SN
      REAL
     &  FILTOBS_TRANSSN_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_TRANSREF_UPD(MXLAMBIN_FILT,MXFILT_ALL)
     & ,FILTOBS_ZPOFF_UPD(MXFILT_ALL)

c filter subdir is
c    [PREFIX_UPD_FILTDIR][SNID][SUFFIX_UPD_FILTDIR]
c and filter filenames are
c    [PREFIX_TRANSSN][filt][SUFFIX_UPD_TRANSSN]

      character
     &   PREFIX_UPD_TRANSSN*80         ! Filename prefix for SN trans
     &  ,PREFIX_UPD_TRANSREF*80
     &  ,PREFIX_UPD_FILTDIR*80
     &  ,SUFFIX_UPD_TRANSSN*80
     &  ,SUFFIX_UPD_TRANSREF*80
     &  ,SUFFIX_UPD_FILTDIR*80
     &  ,FILTER_UPDATE_DIR*(MXCHAR_PATH)  ! directory with filter updates

      LOGICAL FILTINFO_UPD_SN, FILTINFO_UPD_REF

c define common for filter-set per SN
      COMMON / FILTUPDCOM2 /
     &   FILTOBS_TRANSSN_UPD, FILTOBS_TRANSREF_UPD
     &  ,FILTOBS_ZPOFF_UPD
     &  ,PREFIX_UPD_FILTDIR,  SUFFIX_UPD_FILTDIR
     &  ,PREFIX_UPD_TRANSSN,  SUFFIX_UPD_TRANSSN
     &  ,FILTINFO_UPD_SN
     &  ,PREFIX_UPD_TRANSREF, SUFFIX_UPD_TRANSREF
     &  ,FILTINFO_UPD_REF
     &  ,FILTER_UPDATE_DIR


c Define common for filter set mapping.
c There are two maps:
c   MAP1: subdir name vs. index
c   MAP2: indx vs. SNID

      INTEGER MXMAP1_FILTER_UPDATE, MXSNLC_FILTUPD
      PARAMETER ( MXMAP1_FILTER_UPDATE = 20 )
      PARAMETER ( MXSNLC_FILTUPD = 20000 ) ! replaces MXSNLC_FILES

c MAP1:
      INTEGER
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX(MXMAP1_FILTER_UPDATE)
      CHARACTER
     &   MAP1_FILTER_UPDATE_SUBDIR(MXMAP1_FILTER_UPDATE)*100

c MAP2:
c WARNING: works only up to MXSNLC_FILTUPD << MXSNLC

      INTEGER
     &   NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1(MXSNLC_FILTUPD)  ! points to MAP1 index
      CHARACTER
     &   MAP2_FILTER_UPDATE_CCID(MXSNLC_FILTUPD)*(MXCHAR_CCID)  ! CCID list

      COMMON / FILTUPD_MAPCOM /
     &   NMAP1_FILTER_UPDATE
     &  ,MAP1_FILTER_UPDATE_INDX, MAP1_FILTER_UPDATE_SUBDIR
c
     &  ,NMAP2_FILTER_UPDATE
     &  ,MAP2_FILTER_UPDATE_PTRMAP1, MAP2_FILTER_UPDATE_CCID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &   IFILT_OBS, IFILT, ILAM, LEN_SURVEY, OPT_FRAME
     &  ,LEN1, LEN2, LEN_NAME, ISTAT, NLAM, OPTMASK
     &  ,NZBIN, OPT_FILTER_UPDATE_SAVE

      REAL*8
     &   LAM(MXLAMBIN_PRIM)
     &  ,VALa(MXLAMBIN_PRIM)
     &  ,VALb(MXLAMBIN_PRIM)
     &  ,LAMSHIFT, MAGPRIM, LAMRANGE(2)
     &  ,ZMIN, ZMAX, LOGZDIF, RVMW

      CHARACTER
     &   tmpname*40
     &  ,SURVEY_NAME_FILTER*(2*MXCHAR_SURVEY)
     &  ,TMP_FITMODEL*(MXCHAR_FILENAME)
     &  ,BLANK*8, CFILT1*2, cfilt*(MXFILT_ALL)

      LOGICAL LBX

c functions

      INTEGER
     &   RESET_SEDMODEL
     &  ,INIT_PRIMARY_SEDMODEL
     &  ,INIT_FILTER_SEDMODEL
     &  ,INIT_GENMAG_SALT2
     &  ,INIT_GENMAG_SIMSED
     &  ,INIT_GENMAG_BAYESN

      EXTERNAL
     &   RESET_SEDMODEL
     &  ,INIT_PRIMARY_SEDMODEL
     &  ,INIT_FILTER_SEDMODEL
     &  ,INIT_GENMAG_SALT2
     &  ,INIT_GENMAG_SIMSED
     &  ,INIT_GENMAG_BAYESN
     &  ,init_redshift_sedmodel
     &  ,init_mwxt_sedmodel
     &  ,set_UVLAM_EXTRAPFLUX_SEDMODEL
     &  ,GET_CALIB_PRIMARY_SED   ! refac
     &  ,GET_CALIB_FILTERTRANS   ! refac

C ------------------- BEGIN ---------------

      IERR = 0
      LEN_NAME   = INDEX(FITMODEL_NAME,' ') - 1

c reset SEDMODEL to init and/or erase previous instance
      ISTAT = RESET_SEDMODEL()

c init primary spectrum

      CALL GET_CALIB_PRIMARY_SED(tmpname, NLAM, LAM, VALa, 20)
      ISTAT = INIT_PRIMARY_SEDMODEL(tmpname, NLAM,LAM,VALa,LEN1)

      RVMW = DBLE(RV_MWCOLORLAW)
      CALL init_MWXT_SEDMODEL( OPT_MWCOLORLAW, RVMW ) ;

c set entire redshift range if same filters are used for each SN;
c for SN-dependent filters, set exact z-range (and 1 Z-bin)
c to avoid lots of uncecessary CPU time.

      IF ( IFLAG .EQ. 0 .or. DOFIT_PHOTOZ ) THEN
        zmin    = CUTWIN_REDSHIFT(1)
        zmax    = CUTWIN_REDSHIFT(2)

        zmin    = max(zmin,0.005)
        zmax    = min(zmax,3.0)   ! avoid crazy Zmax = E4

        if ( DOFIT_PHOTOZ ) then
          ZMAX = PHOTOZ_RANGE_KCOR(2)
          ZMAX = min ( ZMAX, PHOTOZ_BOUND(2) )
        endif

        logzdif = log10(zmax) - log10(zmin)
        NZBIN    = int(100.* logzdif) + 1
      ELSE
        zmin = SNLC_REDSHIFT
        zmax = SNLC_REDSHIFT
        NZBIN = 1
      ENDIF

      CALL init_redshift_sedmodel(NZBIN, zmin, zmax)

c now init each filter.
      IF ( IFLAG .EQ. 0 ) THEN
         OPT_FILTER_UPDATE_SAVE = OPT_FILTER_UPDATE
         OPT_FILTER_UPDATE      = 0 ! needed to read kcor-filters
      ENDIF

      DO 44 ifilt  = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt1    = filtdef_string(ifilt_obs:ifilt_obs)

         LAMSHIFT = DBLE(FILTOBS_LAMSHIFT(ifilt_obs))

c pass ifilt_obs; everything else is returned.
c VALa = transSN, VALb = transREF8

             ! refactored C code
         OPT_FRAME = OPT_FILTOBS - 1 ! fortran -> C
         CALL GET_CALIB_FILTERTRANS(OPT_FRAME, ifilt_obs,     ! (I)
     &           SURVEY_NAME_FILTER, CFILT, MAGPRIM,            ! (O)
     &           NLAM, LAM, VALa, VALb,                         ! (O)
     &           40, 40 )

         LEN1  = INDEX(cfilt,char(0))
         LEN2  = INDEX(SURVEY_NAME_FILTER,char(0))
         ISTAT = INIT_FILTER_SEDMODEL(IFILT_OBS, cfilt,
     &              SURVEY_NAME_FILTER,
     &              MAGPRIM, NLAM, LAM, VALa, VALb, LAMSHIFT,
     &              LEN1, LEN2 )

      CALL FLUSH(6)

44    CONTINUE  ! end of IFILT loop


      IF ( IFLAG .EQ. 0 ) THEN
         OPT_FILTER_UPDATE  = OPT_FILTER_UPDATE_SAVE
      ENDIF

      CALL set_UVLAM_EXTRAPFLUX_SEDMODEL(UVLAM_EXTRAPFLUX)

c ----------------------------------------
c now do general model-dependent init.
c TMP_FITMODEL has the special end-string char(0) need for C functions.

      TMP_FITMODEL = FITMODEL_NAME(1:LEN_NAME) // char(0)
      BLANK        = "" // char(0)

      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN

        OPTMASK = 0
        IF ( REQUIRE_DOCANA > 0 )           OPTMASK = OPTMASK + 2
        IF ( .NOT. ENABLE_MAGSHIFT_SALT2  ) OPTMASK = OPTMASK + 4
        IF ( .NOT. ENABLE_WAVESHIFT_SALT2 ) OPTMASK = OPTMASK + 8
        IF ( .NOT. ALLOW_NEGFLUX_SALT2    ) OPTMASK = OPTMASK + 16 ! Mar 2021
        IF ( DEBUG_FLAG == 1024 ) OPTMASK = OPTMASK + 1024 ! SALT2 debug flag

        ISTAT = INIT_GENMAG_SALT2( TMP_FITMODEL, BLANK, OPTMASK,
     &            LEN_NAME, 40 )

c turn on covariance model by default,
c unless user specifically sets OPT_COVAR=0
        IF ( OPT_COVAR_FLUX .EQ. -9 ) OPT_COVAR_FLUX    = 1
        if ( .not. USE_MODEL_MAGERR ) OPT_COVAR_FLUX    = 0

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_BAYESN ) THEN

c       BAYESN BLOCK created Nov 2022
        OPTMASK = 1024  ! disable intrinsic scatter
        ISTAT = INIT_GENMAG_BAYESN( TMP_FITMODEL, OPTMASK,
     &            LEN_NAME )

c turn on covariance model by default,
c unless user specifically sets OPT_COVAR=0
        IF ( OPT_COVAR_FLUX .EQ. -9 ) OPT_COVAR_FLUX    = 1
        if ( .not. USE_MODEL_MAGERR ) OPT_COVAR_FLUX    = 0


      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SIMSED ) THEN

cc         ISTAT = INIT_GENMAG_SIMSED( TMP_FITMODEL, LEN_NAME )

      ELSE
         LEN1 = INDEX(FITMODEL_VERSION,' ') - 1
         C1ERR = 'Invalid FITMODEL_VERSION = '
     &                 // FITMODEL_VERSION(1:LEN1)
         C2ERR = 'Model must be based on spectral surface(s).'
         CALL MADABORT("SEDMODEL_INI", c1err, c2err)
      ENDIF

      LKCOR_AVWARP  = .FALSE.
      OPTMASK = 1
      CALL GET_LAMRANGE_SEDMODEL(OPTMASK,LAMRANGE(1),LAMRANGE(2))
      RESTLAMBDA_MODEL(1) = SNGL(LAMRANGE(1))
      RESTLAMBDA_MODEL(2) = SNGL(LAMRANGE(2))

      CALL FLUSH(6)
      RETURN
      END   ! end SEDMODEL_INI


C =====================
CDECK  ID>,  GTCHEAT. 
      SUBROUTINE GET_SIMCHI2_CHEAT()

c Created Feb 2, 2014
c
c Call FCNSNLC with  IFLAG = FCNFLAG_USESIM to replace the
c fitted parameters with the true simulated parameters.
c Store resulting chi2 in global SIMCHI2_CHEAT.
c This works fine for 4-parameter fits, but there is a
c subtle issue for 5-par (photo-z) fits; if the true
c redshift (ZSIM) is very far away from the fitted ZPHOT
c then the wrong filters are used and the program will abort.
c For example, ZPHOT=.4 will use z-band, but if ZSIM=0.1
c then z-band goes outside the 9200 range of SALT2 and
c will abort.
c
c If any obs-frame filter is undefined in the rest-frame
c [ based on range of LAMOBS/(1+ZSIM) ] then skip chi2
c computation and set SIMCHI2_CHEAT = -1 * NFILT_UNDEFINED
c
c Apr 4 2018: fix bug, RESTLAMBDA_MODEL -> RESTLAMBDA_FITRANGE
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c+CDE,SNLCINP.

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      LOGICAL   USED, LAM1, LAM2
      INTEGER   ifilt, IFILT_OBS, NFILT_UNDEFINED
      CHARACTER cfilt*2
      DOUBLE PRECISION GRAD(MXFITPAR), ZSIM, Z1SIM, LAMREST

c function(s)
      DOUBLE PRECISION  USRFUN   ! for SIMCHI2_CHEAT
      EXTERNAL          USRFUN

C ---------------- BEGIN -----------------

c first check that each filter used in the fit
c is defined by the model in the rest frame.

      NFILT_UNDEFINED = 0
      Z1SIM  = 1.0 + SIM_REDSHIFT_HELIO
      DO 100 ifilt     = 1, NFILTDEF_SURVEY

         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt     = filtdef_string(ifilt_obs:ifilt_obs)
         USED      = USE_FILT(ifilt_obs)  ! used in nominal fit
         if ( .NOT. USED ) GOTO 100

         LAMREST = FILTOBS_LAMAVG(ifilt_obs)/Z1SIM
         LAM1    = LAMREST .GE. RESTLAMBDA_FITRANGE(1)
         LAM2    = LAMREST .LE. RESTLAMBDA_FITRANGE(2)

         if ( .not. (LAM1 .and. LAM2) ) THEN
            NFILT_UNDEFINED = NFILT_UNDEFINED + 1

            write(6,30) SNLC_CCID, cfilt(1:1), SIM_REDSHIFT_HELIO
 30         format(T3,'WARNING: CID ', A8,' has ',
     &        A,'-band undefined for SIMCHI2_CHEAT(zsim=',F5.3,')' )
            call flush(6)
         endif

 100  CONTINUE

c bail if there are any undefined filters in the rest-frame.
      if ( NFILT_UNDEFINED > 0 ) THEN
         SIMCHI2_CHEAT = -1.0 * DBLE(NFILT_UNDEFINED)
         return
      endif

c if we get here, filters are OK so compute SIMCHI2_CHEAT.

      CALL FCNSNLC(NFITPAR_MN, GRAD, SIMCHI2_CHEAT,
     &     INIVAL, FCNFLAG_USESIM, USRFUN)

      RETURN
      END    ! end of GET_SIMCHI2_CHEAT

C ===================================================
CDECK  ID>,  PHOTOZ_ANA. 
      SUBROUTINE PHOTOZ_ANA ( IFLAG, iter, ERRFLAG )
c
c Created Aug 2009 by R.Kessler
c Analyze PHOTOZ fit.
c
c On ITER=0, init & print ZDROP for each filter.
c    Also remove SNANA-Trest cuts and store cuts in PHOTOZ-cut variables
c
c On 1st iteration, check for filters to drop.
c On 2nd iteration, do nothing but fill global variables.
c
c If filter(s) are dropped, set ERRFLAG = -1
c so that the 1st iteration is repeated (LREPEAT_ITER=T)
c
c Fill global variables
c  PHOTODZ_MIN(iter)   MIN distance to model-boundary over all filters,
c  PHOTODZ1Z_MIN(iter)
c  IFILT_NEARDROP     ! filter-index closest to being dropped
c
c
c -----------------------------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


c subroutine args

      INTEGER
     &   IFLAG   ! (I) 0= one time init; 1= each SN
     &  ,iter    ! (I) fit iteration: 1,2, ... NFIT_ITERATION
     &  ,ERRFLAG  ! (O)

c local var

      REAL*8
     &   PHOTOZ_VAL, PHOTOZ1_VAL, PHOTOZ_ERR, Z, ZZ
     &  ,LAMOBS, LAMREST
     &  ,ZMIN, Z1MIN,  DZatMIN, DZ1ZatMIN
     &  ,ZMAX, Z1MAX,  DZatMAX, DZ1ZatMAX
     &  ,MJD, PEAKMJD, Trest, Z1
     &  ,ZMIN_KCOR, ZMAX_KCOR, ZBIN_KCOR

      REAL
     &   CUTWIN_SNANA(2)
     &  ,TLIST(MXEPOCH)
     &  ,Z4

      INTEGER
     &   IFILT, IFILT_OBS, N, NFILT_CUT, NFILT
     &  ,IFITDATA, NTLIST, iep, LCID, MSKCUT
     &  ,FLIST(MXEPOCH)
     &  ,NFILTDROP, IFILTDROP
     &  ,NTCUT, LENF

      LOGICAL   LCUT, LDMP, LZTEST, LDROP, LADD
      CHARACTER cfilt1*12, cfiltdrop*12, cfiltadd*12, ccid*(MXCHAR_CCID)
      character VERB*8

c function
      REAL TRESTzCUT
      LOGICAL LFITFUN_FILT, LTEST_ZPHFILTER

      EXTERNAL GET_KCOR_ZRANGE  ! sntools_calib.c[h]

c ------------------ BEGIN --------------

c check for cheater flag.
      IF ( IFLAG .EQ. 0 .and. ITER .EQ. 0 ) THEN
        IF ( BTEST(OPT_PHOTOZ,BIT_PHOTOZ_CHEAT) ) THEN
           DOFIT_PHOTOZ_CHEAT = .TRUE.       ! set global flag
           OPT_PHOTOZ = IBSET(OPT_PHOTOZ,BIT_PHOTOZ_GAUSS)  ! set host-prior bit to be safe
        ELSE
           DOFIT_PHOTOZ_CHEAT = .FALSE.
        ENDIF

        IF ( USE_KCOR_REFACTOR ) THEN
          PHOTOZ_RANGE_KCOR(1) = CUTWIN_REDSHIFT(1)
          PHOTOZ_RANGE_KCOR(2) = CUTWIN_REDSHIFT(2)
          if ( LREST_FITMODEL ) then
             CALL GET_KCOR_ZRANGE(ZMIN_KCOR, ZMAX_KCOR, ZBIN_KCOR)
             PHOTOZ_RANGE_KCOR(1) = ZMIN_KCOR
             PHOTOZ_RANGE_KCOR(2) = ZMAX_KCOR + 4.0*ZBIN_KCOR
          endif
        ENDIF

      ENDIF  ! end IFLAG==0

      ERRFLAG = 0  ! default is OK
      LDROP = .FALSE.
      LADD  = .FALSE.

c bail if we just did 2-band FITRESTMAG since it makes no sense to repeat.
      if( IFILTOBS_BRACKET(1) > 0 ) RETURN

      if ( IFLAG .GT. 0 ) THEN
        CCID = SNLC_CCID
        LCID = ISNLC_LENCCID
      ENDIF

      IF ( ITER > 0 ) THEN
        PHOTODZ_MIN(iter)    = 9999.
        PHOTODZ1Z_MIN(iter)  = 9999.
        PHOTOZ_VAL           = FITVAL(IPAR_ZPHOT,iter)
        PHOTOZ_ERR           = FITERR(IPAR_ZPHOT,iter)
        PHOTOZ1_VAL          = 1. + PHOTOZ_VAL
      ENDIF

c check LREPEAT after PHOTOZ_VAL/ERR are defined
      IF ( LREPEAT_ITER ) THEN
        GOTO 800     ! never process repeated iteration
      ENDIF

      IFILT_NEARDROP       = -9
      LDMP = LDMP_PHOTOZ_DROPFILTER

      if ( ITER .EQ. 0 ) then

        print*,' '
        print*,
     &   '  APPLY THESE TREST-RELATED CUTS BEFORE/AFTER PHOTOZ FIT: '
        call flush(6)

        Z  = PHOTOZ_BOUND(2)
        ZZ = 1. + PHOTOZ_BOUND(2)
        Z4 = SNGL(Z)

        cutwin_snana(1) = TRESTzCUT(1, Z4, CUTWIN_Trest(1) )
        cutwin_snana(2) = TRESTzCUT(2, Z4, CUTWIN_Trest(2) )
        CALL PHOTOZ_SAVECUT('TREST',
     &     cutwin_trest, cutwin_snana, FITANA_cutwin_trest )

        cutwin_snana(1) = TRESTzCUT(1, Z4, CUTWIN_Trestmin(1) )
        cutwin_snana(2) = TRESTzCUT(2, Z4, CUTWIN_Trestmin(2) )
        CALL PHOTOZ_SAVECUT('TRESTMIN',
     &     cutwin_trestmin, cutwin_snana, FITANA_cutwin_trestmin )

        cutwin_snana(1) = TRESTzCUT(1, Z4, CUTWIN_Trestmax(1) )
        cutwin_snana(2) = TRESTzCUT(2, Z4, CUTWIN_Trestmax(2) )
        CALL PHOTOZ_SAVECUT('TRESTMAX',
     &     cutwin_trestmax, cutwin_snana, FITANA_cutwin_trestmax )

        cutwin_snana(1) = TRESTzCUT(1, Z4, CUTWIN_T0gapmax(1) )
        cutwin_snana(2) = TRESTzCUT(2, Z4, CUTWIN_T0gapmax(2) )
        CALL PHOTOZ_SAVECUT('T0GAPMAX',
     &     cutwin_t0gapmax, cutwin_snana, FITANA_cutwin_t0gapmax )

        cutwin_snana(1) = TRESTzCUT(1, Z4, CUTWIN_Tgapmax(1) )
        cutwin_snana(2) = TRESTzCUT(2, Z4, CUTWIN_Tgapmax(2) )
        CALL PHOTOZ_SAVECUT('TGAPMAX',
     &     cutwin_tgapmax, cutwin_snana, FITANA_cutwin_tgapmax )

c change SNANA-Trest cuts

        print*,' '
        print*,'  FIRST-ITERATION FILTER SELECTION: '
        call flush(6)
      endif

      IF( LDMP .and. (ITER .EQ. 1) .and. (.NOT. LREPEAT_ITER) ) then
         print*,' ----------------------------------------------- '
         print*,'  DROP-FILTER DUMP for CID = ' , CCID
      ENDIF

      NFILTDROP = 0
      cfiltdrop = ''
      cfiltadd  = ''

      DO 100 ifilt   = 1, NFILTDEF_SURVEY
          ifilt_obs  = IFILTDEF_MAP_SURVEY(ifilt)
          cfilt1     = filtdef_string(ifilt_obs:ifilt_obs)

c only check FILTLIST_FIT filters specified by user
          if ( .NOT. DOFIT_FILT(ifilt_obs) ) goto 100

          LAMOBS = FILTOBS_LAMAVG(ifilt_obs)

c get min/max redshift allowed by model
          ZMIN = LAMOBS/RESTLAMBDA_USEFIT(2) - 1.0
          ZMAX = LAMOBS/RESTLAMBDA_USEFIT(1) - 1.0

c print filter range in ITER=0 only
          if ( ITER .EQ. 0 ) then
             write(6,600) cfilt1(1:1), ZMIN, ZMAX
600          format(T6,'Keep ',A,' if ', F7.3,' < Zphot < ', F7.3 )
             call flush(6)
             goto 100
          endif

c store valid z-range in global
          PHOTOZ_DROPFILTER_MIN(ifilt_obs) = ZMIN
          PHOTOZ_DROPFILTER_MAX(ifilt_obs) = ZMAX

          Z1MIN = 1. + ZMIN
          Z1MAX = 1. + ZMAX

c note that negative DZ always means outside the ZMIN/ZMAX range
c defined by the model.

          DZatMIN   = (PHOTOZ_VAL - ZMIN) ! should be roughly positive
          DZatMAX   = (ZMAX - PHOTOZ_VAL) ! idem
          DZ1ZatMIN = (PHOTOZ_VAL - ZMIN) / Z1MIN
          DZ1ZatMAX = (ZMAX - PHOTOZ_VAL) / Z1MAX

c keep track of filter that is closest to getting dropped.
          if ( abs(DZatMIN) < abs(PHOTODZ_MIN(iter)) ) then
            PHOTODZ_MIN(iter)   = DZatMIN
            PHOTODZ1Z_MIN(iter) = DZ1ZatMIN
            IFILT_NEARDROP      = IFILT_OBS
          endif

          if ( abs(DZatMAX) < abs(PHOTODZ_MIN(iter)) ) then
            PHOTODZ_MIN(iter)   = DZatMAX
            PHOTODZ1Z_MIN(iter) = DZ1ZatMAX
            IFILT_NEARDROP      = IFILT_OBS
          endif

c apply cut to see if this filter should be tossed;

          LCUT = .FALSE.
          IF ( DZatMIN   .LT. PHOTODZ_REJECT   ) LCUT = .TRUE.
          IF ( DZatMAX   .LT. PHOTODZ_REJECT   ) LCUT = .TRUE.
          IF ( DZ1ZatMIN .LT. PHOTODZ1Z_REJECT ) LCUT = .TRUE.
          IF ( DZ1ZatMAX .LT. PHOTODZ1Z_REJECT ) LCUT = .TRUE.

c set cut logical only on first iteration
          IF ( ITER .EQ. 1 .and. .not. LREPEAT_ITER ) then
             PHOTOZ_DROPFILTER(ifilt_obs) = LCUT
             if ( LCUT  ) then
                ERRFLAG   = -1          ! set repeat flag
                NFILTDROP = NFILTDROP + 1  ! local counter
                LENF = index(cfiltdrop,' ') -1
                cfiltdrop = cfiltdrop(1:LENF) // cfilt1(1:1)
                LDROP = .TRUE.
             endif
          ENDIF

          if ( LDMP ) then
            print*,'  DROPFILTER(', cfilt1(1:1), ') = ', LCUT
            write(6,666) ZMIN, ZMAX, DZatmin, DZatMAX
666         format(T10,'ZMIN,ZMAX=',2F6.3, 3x, 'DZatMIN/MAX=',2F7.3)
            CALL FLUSH(6)
          endif

c 4/24/2011: check if a filter will be added
          LZTEST =  LFITFUN_FILT(ifilt_obs,PHOTOZ_VAL)
          if ( LZTEST .and. .not. USE_FILT(ifilt_obs) ) then
             PHOTOZ_ADDFILTER(ifilt_obs) = .TRUE.
             ERRFLAG  = -1          ! set repeat flag
             LENF = index(cfiltadd,' ') -1
             cfiltadd = cfiltadd(1:LENF) // cfilt1(1:1)
             LADD = .TRUE.
          endif

c          print*,'  xxxx ITER=', ITER,
c     &          '   USE_FILT(', cfilt1(1:1), ') = ', USE_FILT(ifilt_obs),
c     &          '   LZTEST=', LZTEST,
c     &          '   DROP=', PHOTOZ_DROPFILTER(ifilt_obs)

100   CONTINUE  ! IFILT loop over all filters


      IF ( ITER .EQ. 0 ) RETURN

c On last iteration, set NEARDROP-filter index to negative
c if it was dropped. This is to identify dropped filters
c in the analysis-ntuple (ntid 7788)

      LCUT = PHOTOZ_DROPFILTER(IFILT_NEARDROP)
      IF ( ITER .EQ. NFIT_ITERATION .and. LCUT ) THEN
         IFILT_NEARDROP = -IFILT_NEARDROP
      ENDIF


c if filters are dropped, then check if Trest-related
c SNANA cuts are still satisfied. If not, set ERRFLAG
c to SKIP this turkey. Use the loose snana cuts instead of the
c tighter (final) cuts.

      IF ( ERRFLAG .EQ. -1 ) THEN

        VERB = ''
        IF( LDROP ) THEN
           VERB = 'Dropped'
           CFILT1 = cfiltdrop
        ENDIF
        IF( LADD  ) THEN
           VERB = 'Added'
           CFILT1 = cfiltadd
        ENDIF

        if ( STDOUT_UPDATE ) then
          LENF = index(CFILT1,' ') - 1
          write(6,190) VERB, CCID(1:LCID), cfilt1(1:LENF)
190       format(T8, A, 2x, A,'-', A,
     &               ' : retest Trest-related cuts: ', $ )
          call flush(6)
        endif

        PEAKMJD = FITVAL(IPAR_PEAKMJD,iter)
        Z1      = FITVAL(IPAR_ZPHOT,iter)  + 1.0
        NTLIST = 0
        DO 200 ifitdata = 1, NFITDATA

          iep       = EPLIST_FIT(ifitdata)
          ifilt_obs = I4EP_ALL(iep,IEP_IFILT_OBS)

          if ( PHOTOZ_DROPFILTER(ifilt_obs) ) GOTO 200

          MJD           = SNLC8_MJD(iep) - MJDOFF
          Trest         = (MJD - PEAKMJD) / z1
          NTLIST        = NTLIST + 1
          TLIST(NTLIST) = Trest
          FLIST(NTLIST) = ifilt_obs

200     CONTINUE

c if we don't have enough measurements after filter-drop, bail ASAP.
        if ( NTLIST .LT. CUTWIN_NEPOCH(1) ) then
          ERRFLAG = ERRFLAG_ZFIT_DROPFILTCUTS
          return
        endif

c get Nfilt passing Trestmin & Trestmax cuts.

        CALL GET_TRESTVAR (
     &        NTLIST, TLIST, FLIST          ! (I) Trest & IFILT arrays
     &       ,CUTWIN_TREST                  ! (I) user cutwin
     &       ,CUTWIN_TRESTMIN               ! (I) idem
     &       ,CUTWIN_TRESTMAX               ! (I) idem
     &       ,CUTWIN_TREST2                 ! (I)
     &       ,NFILT                         ! (O) Nfilt within TREST-range
     &       ,TRESTMIN_FIT, TRESTMAX_FIT    ! (O) Trestmin,max after fit
     &       ,NFILT_TRESTMIN_FIT            ! (O)
     &       ,NFILT_TRESTMAX_FIT            ! (O)
     &       ,NFILT_TREST2_FIT              ! (O)
     &       ,TGAPMAX_FIT, T0GAPMAX_FIT )   ! (O)


        TRESTRANGE_FIT = TRESTMAX_FIT - TRESTMIN_FIT  ! De 18 2017

c require at least enough filters to have a chance at NFILT_SNRMAX cut

        MSKCUT = 0

        NTCUT = int(CUTWIN_NEPOCH(1))
        if ( NTLIST < NTCUT ) then
          MSKCUT = MSKCUT + 1
          ERRFLAG = ERRFLAG_ZFIT_DROPFILTCUTS
        endif

        NFILT_CUT = int(CUTWIN_NFILT_SNRMAX(1))
        if ( NFILT < (NFILT_CUT-1) ) then
           MSKCUT = MSKCUT + 2
           ERRFLAG = ERRFLAG_ZFIT_DROPFILTCUTS
        endif

        NFILT_CUT = int(CUTWIN_NFILT_SNRMAX2(1))
        if ( NFILT < (NFILT_CUT-1) ) then
           MSKCUT = MSKCUT + 4
           ERRFLAG = ERRFLAG_ZFIT_DROPFILTCUTS
        endif

        NFILT_CUT = int(CUTWIN_NFILT_TRESTMIN(1))
        if ( NFILT_TRESTMIN_FIT < NFILT_CUT )  then
           MSKCUT = MSKCUT + 8
           ERRFLAG = ERRFLAG_ZFIT_DROPFILTCUTS
        endif

        NFILT_CUT = int(CUTWIN_NFILT_TRESTMAX(1))
        if ( NFILT_TRESTMAX_FIT < NFILT_CUT )  then
           MSKCUT = MSKCUT + 16
           ERRFLAG = ERRFLAG_ZFIT_DROPFILTCUTS
        endif

        if ( STDOUT_UPDATE ) then
          if ( ERRFLAG > 0 ) then
             write(6,196) 'FAIL', MSKCUT
          else
             write(6,191) 'PASS'
          endif
          call flush(6)
        endif

191     format(A)
196     format(A,' (MSKCUT=',I3,')' )

c ----------------------
c        print*,' xxxx TRESTMIN, TRESTMAX = ',
c     &          TRESTMIN_FIT, TRESTMAX_FIT
c        print*,' xxxx NFILT(TRESTMIN,TRESTMAX) = ',
c     &          NFILT_TRESTMIN_FIT, NFILT_TRESTMAX_FIT
c ----------------------

      ENDIF  ! end of ERRFLAG = -1

c -------------------------

c after 1st iteration, SKIP SN if photoz no longer respects
c the z-range for each filter.

800   CONTINUE

      IF ( ITER > 1 .OR. LREPEAT_ITER ) THEN
         LZTEST = LTEST_ZPHFILTER(ITER, PHOTOZ_VAL, PHOTOZ_ERR,
     &             IFILTDROP)
         IF ( .NOT. LZTEST ) ERRFLAG = ERRFLAG_ZFIT_RANGE
      ENDIF

      RETURN
      END            ! end of PHOTOZ_ANA

C =================
CDECK  ID>,  LZPHFILT. 
      LOGICAL FUNCTION LTEST_ZPHFILTER(ITER,ZPH,ZPH_ERR,IFILTBAD)
c
c Created Aug 25, 2011 by R.Kessler
c Returns TRUE of all filters respect their photoz range
c defined by PHOTOZ_DROPFILTER_MIN/MAX(ifilt_obs).
c This function is used to weed out fits in which the
c photoz changes dramatically between iterations,
c causing one or more filters to be undefined.
c
c Dec 18, 2011: add IFILTBAD arg.
c
c --------------

      IMPLICIT NONE

      INTEGER ITER            ! (I) fit-iter
      REAL*8  ZPH, ZPH_ERR    ! (I) ZPHOT and its error
      INTEGER IFILTBAD        ! (O) absolute filter index bad filter

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      REAL*8  ZMIN, ZMAX
      INTEGER IFILT, IFILT_OBS, LCID
      LOGICAL LZTEST
      CHARACTER CFILT1*1, CCID*(MXCHAR_CCID)

C ------------- BEGIN -------------

      IFILTBAD        = -9
      LTEST_ZPHFILTER = .TRUE.

      DO 300 ifilt     = 1, NFILTDEF_SURVEY
          ifilt_obs  = IFILTDEF_MAP_SURVEY(ifilt)
          if ( .NOT. USE_FILT(ifilt_obs) ) goto 300

          cfilt1  = filtdef_string(ifilt_obs:ifilt_obs)

          ZMIN = PHOTOZ_DROPFILTER_MIN(ifilt_obs)
          ZMAX = PHOTOZ_DROPFILTER_MAX(ifilt_obs)
          LZTEST = ( ZPH - ZPH_ERR .GE. ZMIN ) .and.
     &             ( ZPH + ZPH_ERR .LE. ZMAX )

          IF ( .NOT. LZTEST ) THEN
            LTEST_ZPHFILTER = .FALSE.
            LCID = ISNLC_LENCCID
            CCID = SNLC_CCID
            write(6,301) CCID(1:LCID), ZPH, cfilt1, ITER
301         format(T2,'WARNING SN=',A,' : PHOTOZ=', F5.3,
     &                 ' is outside range for ',
     &                  A,'-band (ITER=',I1, ') => SKIP ' )
            IFILTBAD = IFILT_OBS
            RETURN
          ENDIF

300   CONTINUE

      RETURN
      END

C ============
CDECK  ID>,  TRESTzCUT. 
      REAL FUNCTION TRESTzCUT(OPT, z, Trest)
      IMPLICIT NONE

c Created Aug 19, 2009
c Returns either 1+z or  1/(1+z) times Trest
c
c OPT = 1 : return TRESTzCUT that is smaller than Trest
c OPT = 2 : return TRESTzCUT that is larger than Trest
c
      INTEGER OPT    ! (I) option
      REAL Z, TREST  ! (I) redshift, Trest

c local

      REAL Z1, Z1FAC

c ----------- BEGIN ----------

      TRESTzCUT = -999.
      Z1 = 1. + z

      IF ( OPT .EQ. 1 ) THEN
        if ( Trest .GE. 0.0 ) then
            Z1FAC = 1./Z1
        else
            Z1FAC = Z1
        endif

      ELSE IF ( OPT .EQ. 2 ) THEN

        if ( Trest .GE. 0.0 ) then
            Z1FAC = Z1
        else
            Z1FAC = 1./Z1
        endif
      ENDIF

      TRESTzCUT = Trest * Z1FAC

      RETURN
      END

C ============================================================
CDECK  ID>,  PHZSAVECUT. 
      SUBROUTINE PHOTOZ_SAVECUT(name,
     &        cutwin_orig, cutwin_snana, cutwin_save )

c Created Aug 15, 2009 by R.Kessler
c
c Save SNANA cut-window in CUTWIN_SAVE; then open
c cutwin_orig to be wide open so that cut is not
c applied in snana.

      IMPLICIT NONE
      CHARACTER NAME*(*)   ! (I) name of cut
      REAL
     &   CUTWIN_ORIG(2)    ! (I) original SNANA cut
     &  ,CUTWIN_SNANA(2)   ! (I) loosened SNANA cut
     &  ,CUTWIN_SAVE(2)    ! (O) address to save orig-snana cut for later

c ------------ BEGIN ---------

      CUTWIN_SAVE(1) = CUTWIN_ORIG(1)
      CUTWIN_SAVE(2) = CUTWIN_ORIG(2)

      CUTWIN_ORIG(1) = CUTWIN_SNANA(1)
      CUTWIN_ORIG(2) = CUTWIN_SNANA(2)

      write(6,20) name, CUTWIN_SNANA
20    format(T8,'Relaxed ',A10,' cut before photoZ fit: ',
     &    F8.3,' to ', F8.3 )

      write(6,30) name, CUTWIN_SAVE
30    format(T8,'Nominal ',A10,' cut after  photoZ fit: ',
     &    F8.3,' to ', F8.3 )

      RETURN
      END

C ====================================================
CDECK  ID>,  SET_ZHD_PHOTOZ. 
      SUBROUTINE SET_ZHD_PHOTOZ()

c Created Jan 26 2018
c Set redshift globals for output tables:
c    SNLC_zHELIO[_ERR]
c    SNLC_zCMB[_ERR]
c    SNLC_zHD[_ERR]
c
c For zHD, translate heliocentric fitted photo into cmb frame,
c and include ZPECERR in zHDERR
c
c ASSUMPTION: HOSTGAL_ZPHOT is in heliocentric frame.
c

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER OPT
      CHARACTER EQ*4
      REAL*8  ZHEL, ZCMB, ZERR, ZERR1, ZERR2

c function
      REAL*8 zhelio_zcmb_translator

C -------------- BEGIN -------------
      OPT   = 1 ! --> convert ZHEL to ZCMB
      EQ    = 'eq' // char(0)
      ZHEL  = DBLE(LCVAL_STORE(IPAR_ZPHOT))
      ZCMB  =
     &   zhelio_zcmb_translator(ZHEL,SNLC8_RA,SNLC8_DEC,EQ,OPT,4)

      ZERR1 = DBLE( LCERR_STORE(IPAR_ZPHOT) )
      ZERR2 = DBLE( SNLC_ZPEC_ERR * ( 1.0 + zCMB ) )
      ZERR  = sqrt(ZERR1*ZERR1 + ZERR2*ZERR2)

      SNLC_ZHELIO     = SNGL(ZHEL)
      SNLC_ZHELIO_ERR = SNGL(ZERR1)

      SNLC_zCMB       = SNGL(ZCMB)
      SNLC_zCMB_ERR   = SNGL(ZERR1) ! do not include vpec error here

      SNLC_zHD        = SNGL(ZCMB)
      SNLC_zHD_ERR    = SNGL(ZERR)  ! include vpec error

      RETURN
      END     ! ene SET_ZHD_PHOTOZ

C ====================================================
CDECK  ID>,  FITANA_MARG. 
      SUBROUTINE FITANA_MARG(isn,DOPDFPLOT,ERRFLAG)
      IMPLICIT NONE
c
c Shell to call MARG_DRIVER
c Returns ERRFLAG=0 (OK) or ERRFLAG > 0 (discard fit)
c
c
c Jul 8, 2009: skip marg if fitprob(before marginalization)
c              fails CUTWIN_NOMARG_PROB(2)
c
c Oct 7,2009: fix logic to avoid fbounds-check with ifilt=0.
c             Code runs the same as before
c
c Oct 20, 2009: add DOPLOT argument  for monitor plots
c
c Nov 11, 2009: add LMCMC option
c
c Mar 2011:
c   skip marginalization if DOCHI2_SIGMA=T and chi2(sigma)
c   fails cut since it won't change after marg.
c
c Dec 18, 2011:
c  - add ISTAT arg
c  - LZPHOT = LTEST_ZPHFILTER after marginalization and set
c    ISTAT=0 if a filter is dropped => discard fit
c
c Jan 4, 2013: replace ISTAT with ERRFLAG
c              Success is now ERRFLAG=0 rather than ISTAT=1.
c
c -----------
      INTEGER ISN       ! (I) SN sparse index
      LOGICAL DOPDFPLOT ! (I) T => make PDF monitor plots
      INTEGER ERRFLAG   ! (O) returns 0=> OK, >0 => discard

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,MCMCCOM. inserted below by ypatchy. 

c Created Nov 2009 for Ben Dilday's  MCMC method

c a bunch of MCMC stuff
      LOGICAL LMCMC
     &  ,LTUP_MCMC    ! book/fill special ntuple

      INTEGER
     &   NMCMC_EVAL        ! number of total evaluations for MCMC
     &  ,IMCMC_FLAG        ! a generic flag for MCMC variations
     &  ,NMCMC_CHAINS      ! number of chains to run
     &  ,NMCMC_BURN        ! size of burn in
     &  ,IMCMC_STORE       ! store every nth chi2 in the ntuple

      CHARACTER
     &  CHOPT_MCMC*16     ! ??

      REAL
     &   MCMC_NSIG_STEP   ! ??
     &  ,NSIG_MCMC_START  ! ??

      COMMON / SNFMCMC / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN,MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START

      NAMELIST / MCMCINP / NMCMC_EVAL, IMCMC_FLAG
     &     ,NMCMC_CHAINS, NMCMC_BURN, MCMC_NSIG_STEP
     &     ,CHOPT_MCMC, LMCMC, LTUP_MCMC
     &     ,IMCMC_STORE, NSIG_MCMC_START


C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK



      REAL NSIGMA, Z1
      INTEGER
     &   OPT, HOFF, iep, ifilt, ifilt_obs, NDOF, LL
     &  ,ITER, IFILTBAD

      LOGICAL LTMP

      REAL FITPROB, CHI2
      LOGICAL  LFITPROB, LMARG, LZPHOT

      REAL*8  CHI8, ZPH8, ZPHERR8

      CHARACTER CFILT1*1

c functions
      REAL    LCPROBCHI2
      REAL*8  PROB_CHI2NDOF
      LOGICAL LTEST_ZPHFILTER

C --------------- BEGIN ---------------

      ERRFLAG = 0  ! init to OK

c store filter-dependent chi2 before continuing
c These are just the fit chi2 from minimization.

      DO ifilt = 0, NFILTDEF_SURVEY

         if ( ifilt .GT. 0 ) then
            ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
            LTMP      = USE_FILT(ifilt_obs)
         else
            LTMP = .FALSE.
         endif

         if ( ifilt .EQ. 0 .or. LTMP ) then
           NDOF = NEPOCH_FIT(ifilt) - NFITPAR(ifilt)
           LC_FITCHI2(ifilt)  = FCN_FITCHI2(ifilt)
           LC_MARGCHI2(ifilt) = FCN_FITCHI2(ifilt)

           CHI8 = DBLE(LC_FITCHI2(ifilt))
           LC_FITPROB(ifilt)  = PROB_CHI2NDOF(CHI8, NDOF)
           LC_MARGPROB(ifilt) = LC_FITPROB(ifilt)
         endif

      ENDDO  ! ifilt

      LMARG = NGRID_PDF .GT. 0

      IF ( LMCMC .and. LMARG ) THEN
        c1err = 'Cannot marginalize and use MCMC'
        c2err = 'Choose one or the other (not both!)'
        CALL MADABORT("FITANA_MARG", c1err, "")
      ENDIF


c make sure that either MARGINALIZATION or MCMC is specified.

      IF ( .not. ( LMCMC .or. LMARG ) ) RETURN

c ---------------------------------------------------------
c skip marginalization if fitted chi2-prob fails cut

      LL = ISNLC_LENCCID

      FITPROB  = LCPROBCHI2_STORE(1)  ! fitprob before marginalization
      LFITPROB = ( FITPROB .GT. FITWIN_NOMARG_PROB(1) )
      IF ( .NOT. LFITPROB ) THEN
        write(6,600) 'FITPROB', SNLC_CCID(1:LL), FITPROB
        RETURN
      ENDIF

600     format(t5,A,'(CID ',A,') = ',G12.4,
     &       ' FAILS CUT => SKIP MARGINALIZATION' )

c skip marg if chi2(sigma) fails cut since it won't change after marg.
      CHI2 = FITCHI2_STORE(4)
      LTMP = (CHI2 .GE. FITWIN_CHI2SIGMA(1) ) .and.
     &       (CHI2 .LE. FITWIN_CHI2SIGMA(2) )

      IF ( DOCHI2_SIGMA .and. .not. LTMP ) THEN
        write(6,600) 'CHI2SIGMA', SNLC_CCID(1:LL), CHI2
        RETURN
      ENDIF

c ---------------------------------------------------------

      IF ( DOPDFPLOT ) THEN
         HOFF   = 700                ! hbook offset for 1d pdf plots
      ELSE
         HOFF = 0
      ENDIF

c Check for too-tiny errors.
      CALL FITERR_ADJUST()

c marginalize !

      IF ( LMARG ) THEN

        NSIGMA = float(NSIGMA_PDF)
        OPT    = OPT_INTEGPDF_FULL  ! default is full chi2 evaluation

c now check for reasons to quit FCNSNLC early (to save CPU time)

        IF ( OPT_COVAR_FLUX .LE. 0 .or. COVMAT_MIN .GE. 0.0 ) then
          OPT = OPT_INTEGPDF_QUITCHI2
        ENDIF

        CALL MARG_DRIVER(HOFF, OPT,
     &                MAX_INTEGPDF, NGRID_PDF, NSIGMA )

c   for PHOTOZ fit, check if filters were added/dropped which
c   can happen if photoZ_marg - photoZ_fit is  large enough.

        IF ( DOFIT_PHOTOZ ) THEN
          ZPH8    = LCVAL_STORE(IPAR_zPHOT)
          ZPHERR8 = 0.0
          ITER    = NFIT_ITERATION+1
          LZPHOT  = LTEST_ZPHFILTER(ITER, ZPH8, ZPHERR8, IFILTBAD)
          if ( .NOT. LZPHOT ) then
             ERRFLAG = ERRFLAG_ZFIT_RANGE
             return
          endif

        ENDIF

      ELSE IF ( LMCMC ) THEN
         CALL MCMC_DRIVER( HOFF
     &        ,NMCMC_CHAINS, NMCMC_EVAL, NMCMC_BURN
     &        ,LTUP_MCMC, IMCMC_STORE, MCMC_NSIG_STEP
     &        ,NSIG_MCMC_START
     &        )

      ENDIF

c store marginalized chi2 per filter

      DO ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)

         if ( ifilt_obs.GT.0 .and. USE_FILT(ifilt_obs) ) then

           NDOF = NEPOCH_FIT(ifilt) - NFITPAR(ifilt)
           LC_MARGCHI2(ifilt) = FCN_FITCHI2(ifilt)

           LTMP = NDOF .GT. 0 .and. LC_MARGCHI2(ifilt) .GE. 0.0
           if ( LTMP ) then
              CHI8 = DBLE( LC_MARGCHI2(ifilt) )
              LC_MARGPROB(ifilt) = PROB_CHI2NDOF(CHI8, NDOF)
           else
              LC_MARGPROB(ifilt) = 1.0
           endif
         endif
      ENDDO

      RETURN
      END


C ============================================
CDECK  ID>,  FCNSNLC. 
      SUBROUTINE FCNSNLC(NVAR,GRAD,CHI2,XVAL,IFLAG, USRFUN )
c
c User function to be minimized (chi2, log-likelihood, etc ...).
c "USRFUN" is an optional function, for example from MC.
c YOU are responsible to sync XVAL(1:NFITPAR) in this function with
c INIVAL(1:NFITPAR) in FITPAR_PREP and with FITPAR(1_NFITPAR)
c in FITPAR_ANA.
c
c The prior-chi2 "CHI2INI" is used for minimization.
c However, the stored chi2 "FCN_FITCHI2(0)" does NOT include
c CHI2INI so that the probability is based on the data and
c model, and not on the prior.
c
c
c
c The data to compare the function to are in KEEP,SNCUTS
c in snana.car. A few useful variables are
c
c   SNLC_CID         ! CID vs. sparse SN index
c   SNLC_NEPOCH_STORE      ! Number of Epochs
c
c   SNLC_RA          ! RA   vs. SN
c   SNLC_DECL        ! OBDECL vs. SN
c   SNLC_REDSHIFT    ! redshift used for analysis
c
c   SNLC_XTINC_MW(MXFILT_ALL)  ! interstellar extinction
c
c   SNLC_FLUXCAL(MXFILT_OBS,MXEPOCH)
c   SNLC_FLUXCAL_ERRSTAT(MXFILT_OBS,MXEPOCH)
c   SNLC_FLUXCAL_ERRSYST(MXFILT_OBS,MXEPOCH)
c   SNLC_FLUXCAL_ERRTOT(MXFILT_OBS,MXEPOCH)
c
c   chi2 = D_i  COV_ij D_j
c
c
c
c  HISTORY
c ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c
c Mar 1 2017: load R4EP(iep,JEP_MAGDIF)
c
c Jun 23 2019: protect I4EP_ALL array bound
c Jul 13 2019:
c   + compute RATIO_ERR only if LFLAG_USER=T (to reduce compute time)
c   + apply SNR_RAW cut to compute R4SN_FFSUM_XXX
c
c Feb 28 2020:
c   define DELCHI2_NOFUDGE to make test with DELCHI2_REJECT;
c   fixes long-standing bug when FUDGEALL_ITER1_MAXFRAC is set.
c
c ---------------------------------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


c subroutine ars

      INTEGER
     &    NVAR    ! numnber of VARIABLE params only
     &   ,IFLAG

      DOUBLE PRECISION  GRAD(*), XVAL(*), chi2, USRFUN

      EXTERNAL USRFUN

c local arguments

      INTEGER
     &   ISN, ITER, ifilt, ipar, IFILT_obs, epoch, imjd, ifitdata
     &  ,NFITDATA_LOC, irow, icol, IERR
     &  ,NFITDATA_FILT(MXFILT_OBS), NDMPFCN(0:MXFILT_OBS)

      character cfilt*1

      DOUBLE PRECISION
     &   ZSN, ZZ, CHI2INI, SHAPEPAR(2), DISTPAR, COLORPAR
     &  ,x0, S2a, S2b, MU, RVHOST, PEAKMJD, Trest, Tobs
     &  ,AVRV, MWAV, MWEBV, XTAV, XTMW, MJD, MJDFIT
     &  ,flux_data, flux_data_errtot, flux_data_sqerrtot
     &  ,signoise_data, signoise_model
     &  ,flux_model, flux_model_err ,flux_model_sqerr
     &  ,flux_fudge_sqerr, flux_fudge_err, flux_errtot
     &  ,errtmp, arg, RATIO, RATIO_ERR, WGT, MAGDIF, SNR_FIT, SNR_RAW
     &  ,AVwarp, mag_kcor(2), mag_tmp, mag_err
     &  ,dif, sqdif, sqsig, inv_sqsig, sqsig_nofudge
     &  ,delchi2, delchi2_diag, delchi2_sigma, delchi2_nofudge
     &  ,chi2filt_sigma(MXFILT_OBS),chi2sum_sigma,chi2filt(MXFILT_OBS)
     &  ,errfrac, DEL_FLUX(MXFIT_DATA)
     &  ,FF, COV_INV, x1, DT1, DT2, CHI2PRIOR(0:MXFITPAR)
     &  ,LAMAVG, XVAL4COV(MXFITPAR)

      LOGICAL
     &   LFLAG_FIRST_MN  ! first call from MINUIT (IFLAG=2)
     &  ,LFLAG_LAST_MN   ! last call from MINUIT  (IFLAG=3)
     &  ,LFLAG_USER      ! called from user (IFLAG=30)
     &  ,LFLAG_USESIM    ! use SIM params instead of XVAL (IFLAG=99)
     &  ,LFLAG_FAST      ! speed up if possible (for pdf integration)
     &  ,LFLAG_FIT, LFLAG_PRIOR_ONLY, LFLAG_SIGMA_ONLY
     &  ,LAST, LDMPFCN_LOC, LDMPFUN_LOC, LREJECT, LREJECT2, LFITDATA
     &  ,FIRSTFILT, LASTFILT, LMWCOR, LIGNORE, LTMP, LMUFIX, LPOSFLUX
     &  ,FIRST_ITER
     &  ,REJECT_TREST, REJECT_MJD, REJECT_SIGNOISE, REJECT_DELCHI2

      CHARACTER CVAR*8, star*1
      REAL*8 delchi2_off(2000)
      REAL*4 LAMREST4

c functions
      REAL*8
     &   FCNCHI2_PRIOR, FCNCHI2_SIGMA, DLMAG8_REF
     &  ,GET_RV8, GET_DIST8, SALT2xx1

      LOGICAL FIRST_ITERATION

C ----------- BEGIN ------------

      CHI2 = 1.0E7

      LFLAG_FIRST_MN   = IFLAG .EQ.  2   ! first MINUIT call
      LFLAG_LAST_MN    = IFLAG .EQ.  3   ! last MINUIT call here => store info
      LFLAG_FIT        = IFLAG .EQ.  4   !
      LFLAG_USER       = IFLAG .EQ. FCNFLAG_USER ! user-call (NOT from MINUIT)
      LFLAG_USESIM     = IFLAG .EQ. FCNFLAG_USESIM ! use sim params
      LFLAG_FAST       = IFLAG .EQ. FCNFLAG_FAST
      LFLAG_PRIOR_ONLY = IFLAG .EQ. FCNFLAG_PRIOR_ONLY
      LFLAG_SIGMA_ONLY = IFLAG .EQ. FCNFLAG_SIGMA_ONLY

      LAST = LFLAG_LAST_MN .or. LFLAG_USER .or. LFLAG_USESIM
cc      LAST = LFLAG_LAST_MN .or. LFLAG_USESIM ! xxx TEST

      R4SN_FFSUM_DATA  = 0.0
      R4SN_FFSUM_MODEL = 0.0
      R4SN_FFSUM_CROSS = 0.0
      R4SN_FFSUM_WGT   = 0.0
      R4SN_FFSUM_RATIO = 0.0

      IF ( LAST ) THEN
c include rejects on last iter
         NFITDATA_LOC = NFITDATA + NFITDATA_REJECT
      ELSE
         NFITDATA_LOC = NFITDATA
      ENDIF

c extract parameters into local variables

      ITER       = int ( XVAL(IPAR_ITER) )
      ISN        = int ( XVAL(IPAR_ISN)  )
      if ( ITER .EQ. 0 .OR. ISN .EQ. 0 ) RETURN

      FIRST_ITER = FIRST_ITERATION(ITER)

      COLORPAR    = XVAL(IPAR_AV)       !  AV or c
      AVRV        = XVAL(IPAR_AVRV)
      SHAPEPAR(1) = XVAL(IPAR_SHAPE)
      SHAPEPAR(2) = XVAL(IPAR_SHAPE2)
      PEAKMJD     = XVAL(IPAR_PEAKMJD)
      DISTPAR     = XVAL(IPAR_DLMAG)    ! MU or x0
      ZSN         = XVAL(IPAR_zPHOT)
      RVHOST      = GET_RV8(XVAL)
      MWEBV       = DBLE( SNLC_MWEBV )
      MWAV        = MWEBV/RV_MWCOLORLAW

c check for photoZ fit that constrains DLMAG to input cosmology.

      LMUFIX = (DOFIT_PHOTOZ .and. (INISTP_DLMAG .EQ. 0.0) )
      IF ( LMUFIX ) THEN
         DISTPAR = GET_DIST8(ZSN,SHAPEPAR(1),COLORPAR,ONE8)
      ENDIF

      ZZ  = 1.0 + ZSN

      IF ( LFLAG_USESIM .and. LSIM_SNANA ) THEN
         COLORPAR     = SIMVAL_STORE(IPAR_AV)
         RVHOST       = SIMVAL_STORE(IPAR_RV)
         DISTPAR      = SIMVAL_STORE(IPAR_DLMAG)
         SHAPEPAR(1)  = SIMVAL_STORE(IPAR_SHAPE)
         SHAPEPAR(2)  = SIMVAL_STORE(IPAR_SHAPE2)
         PEAKMJD      = SIMVAL_STORE(IPAR_PEAKMJD) - MJDOFF
         ZSN          = SIMVAL_STORE(IPAR_zPHOT)
      ENDIF

c ------------------------------------
c Get initial CHI2 from priors.

      IF ( LFLAG_SIGMA_ONLY ) THEN
        CHI2INI = 0.0
      ELSE
        CHI2INI = FCNCHI2_PRIOR(XVAL,CHI2PRIOR)
      ENDIF

      CHI2    = CHI2INI
      chi2sum_sigma = 0.0

c bail on large CHI2INI unless we are dumping.

      if ( CHI2 .GT. 1.0E7  .and. .not. LDMPFCN(0) ) RETURN
      if ( LFLAG_PRIOR_ONLY ) RETURN

c -------------------------------------------

      DO ifilt = 1, MXFILT_OBS
         CHI2FILT(ifilt)       = 0.0
         CHI2FILT_SIGMA(ifilt) = 0.0
         NFITDATA_FILT(ifilt)  = 0
         NDMPFCN(ifilt)        = 0
      ENDDO
         NDMPFCN(0)        = 0

      FIRSTFILT = .TRUE.

c ------------------------------------

      DO 102 ifitdata   = 1, NFITDATA_LOC

        epoch           = EPLIST_FIT(ifitdata)
        ifitdata_usrfun = ifitdata  ! load common block for USRFUN

        LFITDATA = ifitdata .LE. NFITDATA

        ifilt     = I4EP_ALL(epoch,IEP_IFILT)
        ifilt_obs = I4EP_ALL(epoch,IEP_IFILT_OBS)
        cfilt     = filtdef_string(ifilt_obs:ifilt_obs) ! for debug only

c    protect model against invalid rest-frame lambda values (Mar 29, 2011)
        LAMAVG    = DBLE( FILTOBS_LAMAVG(ifilt_obs) )
        LAMREST4  = SNGL(LAMAVG /ZZ)

        if ( LAMREST4 > RESTLAMBDA_USEFIT(2) ) GOTO 102
        if ( LAMREST4 < RESTLAMBDA_USEFIT(1) ) GOTO 102

        MJD                = R8EP_MJD(ifitdata)
        MJDFIT             = MJD - MJDOFF

        flux_data        = dble ( R4EP_ALL(epoch,JEP_DATAFLUX) )
        flux_data_errtot = dble ( R4EP_ALL(epoch,JEP_DATAFLUX_ERR) )
        flux_fudge_err   = dble ( R4EP_ALL(epoch,JEP_FUDGEFLUX_ERR) )

        flux_fudge_sqerr   = flux_fudge_err   * flux_fudge_err
        flux_data_sqerrtot = flux_data_errtot * flux_data_errtot

c compute data SNR with/without fudged error
        errtmp = dsqrt(flux_data_sqerrtot + flux_fudge_sqerr)
        SNR_FIT   = flux_data / errtmp
        SNR_RAW   = flux_data / flux_data_errtot

        Tobs      = MJDFIT - PEAKMJD    ! observation time, days
        Trest     = Tobs / ZZ

        Nfitdata_filt(ifilt) = Nfitdata_filt(ifilt) + 1
        LASTFILT  = Nfitdata_filt(ifilt) .EQ. NEPOCH_FIT(ifilt)

c set local dump logicals = namelist flag .and. (debug option)

         LDMPFCN_LOC = LDMPFCN(ifilt_obs)
     &        .and. LFITDATA  ! .and. FIRST_ITERATION(ITER)

         if(DOFIT_IDEAL_EVENT .and. DOFIT_IDEAL ) LDMPFCN_LOC = .FALSE. ! xxx DEBUG ONLY

         LDMPFUN_LOC = LDMPFUN(ifilt_obs)
     &           .and. Trest .GE. TREST_DMPFUN(1)
     &           .and. Trest .LE. TREST_DMPFUN(2)
     &           .and. LFITDATA

c dumpe header just once per filter.
         if(LDMPFCN_LOC .and. FIRSTFILT ) then

              print*,' '
              print*,' -------------------------------------- '
              write(6,602) SNLC_CCID,  ITER, IFLAG
602           format(T5,'PREPARE FCNSNLC DUMP for CID= ', A16,
     &              3x,'   (ITER=',I2, 2x, 'IFLAG=',I2, ')' )

c print  fit-pars to see crazy values.

              write(6,603) 'ZSN', ZSN
              write(6,604) 'PEAKMJD', PEAKMJD
              write(6,603)  PARNAME_STORE(IPAR_AV)(1:6), COLORPAR
              if ( INISTP_AVRV .GT. 0.0 ) then
                write(6,603)  PARNAME_STORE(IPAR_AVRV)(1:6), AVRV
                write(6,603)  'RVHOST', RVHOST
              endif

              write(6,603) 'MWAV', MWAV
              write(6,603) 'SHAPE', SHAPEPAR(1)
              write(6,603)  PARNAME_STORE(IPAR_DLMAG)(1:6), DISTPAR

603           format(T7, A, T17,'= ', G14.6 )
604           format(T7, A, T17,'= ', F12.4 )

c print non-zero chi2prior contributions

              print*,' '
              DO ipar = 0, IPAR_MAX
                if ( ipar .EQ. 0 ) then
                    CVAR = 'SIMEFF'
                else
                    CVAR = PARNAME_STORE(ipar)
                endif
                if ( CHI2PRIOR(ipar) .GT. 0.0 ) then
                  write(6,690) CVAR, CHI2PRIOR(ipar)
690               format(T8,'CHI2PRIOR(', A8, ') = ', G12.4 )
                endif
                CALL FLUSH(6)
              ENDDO

c always print total prior-chi2
              print*,'      CHI2PRIOR(TOTAL) = ', SNGL(CHI2INI)

              CALL FLUSH(6)
         endif  ! end of DUMP

         IF ( FIRSTFILT ) FIRSTFILT = .FALSE.

c =====================
c get flux (observer frame) from model
c Note that info on all five filters is passed.

        flux_model =
     &       USRFUN ( ITER, IFILT_OBS, ZSN, Tobs  ! (I)
     &          ,SHAPEPAR           ! (I) delta, stretch, x1 ...
     &          ,DISTPAR            ! (I) MU or x0
     &          ,COLORPAR           ! (I) AV or c
     &          ,RVHOST             ! (I) color law
     &          ,MWEBV              ! (I) MW extinct
     &          ,LDMPFUN_LOC        ! (I)
     &          ,AVwarp             ! (O) AV warp for SEC
     &          ,MAG_KCOR           ! (O) K-correction & error
     &          ,XTAV               ! (O) host-gal extinct in rest-filter
     &          ,XTMW               ! (O) MW extinct in obs-filter (mag)
     &          ,MAG_ERR            ! (O) mag error from model
     &                )

c convert MAG_ERR into flux-error

        errfrac          = 1.0 - TEN8**(-0.4*MAG_ERR)
        flux_model_err   = flux_model * errfrac
        flux_model_sqerr = flux_model_err * flux_model_err

c ---------------------------------------------
c get data-model chi2 ;
c if USE_FITCOV=T, then sum diagonal elements of cov matrix.

        dif      = flux_data - flux_model
        sqdif    = dif * dif

        IF ( USE_FITCOV ) THEN
           sqsig         = 1.0 / covmat2(ifitdata,ifitdata)
           delchi2_diag  = sqdif / sqsig
        ENDIF

c always evaluate simple chi2 ignoring covariance
        sqsig   = flux_data_sqerrtot + flux_model_sqerr
     &          + flux_fudge_sqerr
        sqsig_nofudge = flux_data_sqerrtot + flux_model_sqerr
        inv_sqsig     = 1.0/sqsig

        flux_errtot = dsqrt(sqsig)

        delchi2         = sqdif * inv_sqsig
        delchi2_nofudge = sqdif/sqsig_nofudge
cc xxx mark        IF ( RESTORE_DES3YR ) delchi2_nofudge = delchi2

        IF ( LFLAG_SIGMA_ONLY ) THEN
          delchi2         = 0.0
          delchi2_diag    = 0.0
          delchi2_nofudge = 0.0
        ENDIF

c 5/08/2009: tack on chi2 from model-error (2nd iter only)
        delchi2_sigma = FCNCHI2_SIGMA(iter,epoch,flux_errtot)

        IF ( LFITDATA ) then
          DEL_FLUX(ifitdata)  = dif
          chi2filt(ifilt) = chi2filt(ifilt) + delchi2

          chi2filt_sigma(ifilt) =
     &    chi2filt_sigma(ifilt) + delchi2_sigma

c sum chi2_sigma over all epochs ... sum used only for OPT_COVAR_FLUX > 0
          chi2sum_sigma = chi2sum_sigma   + delchi2_sigma

          if ( USE_FITCOV ) then
             chi2  = chi2  + delchi2_diag   ! diag part of chi2
          else
             chi2  = chi2  + delchi2        ! add conventional chi2
          endif

c always tack on chi2 from log(sigma) term
          chi2  = chi2 + delchi2_sigma

        ENDIF

c if fast-flag is set, quit when chi2 is too big;
c this corresponds to tiny pdf in integral.

        if ( LFLAG_FAST .and.  chi2 .GT. FITCHI2_QUIT ) return

c check dump-flag again; print every epoch here

        if ( LDMPFCN_LOC ) then
            write(6,666) cfilt, Trest, delchi2
     &          ,flux_model, flux_model_err
     &          ,flux_data, flux_data_errtot

666         format(2x,A,  2x, 'Trest=',F6.2, 2x,'dchi2=',F9.5, 2x,
     &        'Fmodel=',E9.3,'+-',E8.3, 2x,
     &        'Fdata=', E9.3,'+-',E8.3  )

            NDMPFCN(0)     = NDMPFCN(0) + 1
            NDMPFCN(ifilt) = NDMPFCN(ifilt) + 1
            CALL FLUSH(6)

        endif

c always store flux for model in case we need to re-compute
c covariance matrix each time. The other EP_XXX arrays are
c computed inside LAST if-block.

        R4EP_ALL(epoch,JEP_MODELFLUX)     = flux_model
        R4EP_ALL(epoch,JEP_MODELFLUX_ERR) = flux_model_err
        R4EP_ALL(epoch,JEP_FLUX_ERRTOT)   = flux_errtot

        IF ( LAST ) THEN

c increment SNRMAX for fitted epochs only
           if ( LFITDATA ) then
             R4BAND_SNRMAX_FIT(ifilt) =
     &          MAX ( R4BAND_SNRMAX_FIT(ifilt), SNR_FIT )
             R4BAND_SNRMAX_RAW(ifilt) =
     &          MAX ( R4BAND_SNRMAX_RAW(ifilt), SNR_RAW )
           endif

           if ( flux_model .GT. 0.0 ) then
             mag_tmp = -2.5 * dlog10(flux_model)   ! model-mag_{obs}
     &               + ZEROPOINT_FLUXCAL_DEFAULT

             R4EP_ALL(epoch,JEP_MODELMAG)     = mag_tmp
             R4EP_ALL(epoch,JEP_MODELMAG_ERR) = mag_err
           endif

           mag_tmp = SNLC_MAG(epoch)
           IF( USE_MWCOR) mag_tmp = mag_tmp - SNLC_MWXT_MAG(ifilt)
           R4EP_ALL(epoch,JEP_DATAMAG)     = mag_tmp
           R4EP_ALL(epoch,JEP_DATAMAG_ERR) = SNLC_MAG_ERRPLUS(epoch)

           R4EP_ALL(epoch,JEP_XTHOST)   = XTAV
           R4EP_ALL(epoch,JEP_MWXT)     = XTMW

           IF ( LREST_FITMODEL ) THEN
             R4EP_ALL(epoch,JEP_KCOR)       = MAG_KCOR(1)
             R4EP_ALL(epoch,JEP_KCOR_ERR)   = MAG_KCOR(2)
             R4EP_ALL(epoch,JEP_AVWARP)     = AVWARP

c xxx remove harmless bug, Jan 2020  arg = 0.4*(MAG_KCOR(1) + SNLC_DLMAG)
             arg = 0.4*(MAG_KCOR(1) + DISTPAR)
             R4EP_ALL(epoch,JEP_DATAFLUX_REST)= flux_data * 10.0**(arg)
           ENDIF


c data/Model ratio
           RATIO=0.0; RATIO_ERR=0.0; MAGDIF=-9.0
           LPOSFLUX = ( abs(flux_model) .GT. 1.0E-21 )
           if ( LPOSFLUX )      RATIO  = flux_data / flux_model
           if ( RATIO > .001 )  MAGDIF = -2.5*log10(RATIO)

           if ( LPOSFLUX .and. LFLAG_USER ) then ! limit calc to USER only
              sqsig = ( flux_data_errtot  / flux_data  )**2
     &              + ( flux_model_err    / flux_model )**2
              errfrac    = dsqrt(sqsig)
              RATIO_ERR  = abs(RATIO) * errfrac
           endif

           sqsig = flux_data_errtot**2 + flux_model_err**2

           R4EP_ALL(epoch,JEP_RATIO)       = RATIO
           R4EP_ALL(epoch,JEP_RATIO_ERR)   = RATIO_ERR
           R4EP_ALL(epoch,JEP_RESID)       = dif
           R4EP_ALL(epoch,JEP_RESID_ERR)   = dsqrt ( sqsig )
           R4EP_ALL(epoch,JEP_MAGDIF)      = magdif
           R4EP_ALL(epoch,JEP_TREST)       = Trest
           R4EP_ALL(epoch,JEP_TOBS)        = Tobs
           R4EP_ALL(epoch,JEP_MJD)         = MJDFIT
           R4EP_ALL(epoch,JEP_DELCHI2)     = DELCHI2
           FCN_FITCHI2(0)          = chi2 - CHI2INI

           DT1 = abs(Trest)
           DT2 = abs( R4BAND_TREST_NEARPEAK(ifilt_obs) )
           if ( DT1 < DT2 ) then
             R4BAND_XTMW_NEARPEAK(ifilt_obs)  = XTMW
             R4BAND_TREST_NEARPEAK(ifilt_obs) = Trest
             I4BAND_EP_NEARPEAK(ifilt_obs)    = epoch
           endif

c check for epochs to reject at end of 1st iteration only (note LAST=T here)

           if ( FIRST_ITER .and. IFLAG <= 4 ) then  ! includes iter=1 repeat

              signoise_data  = flux_data  / flux_data_errtot
              signoise_model = flux_model / flux_data_errtot

              REJECT_TREST   =
     &           (Trest < FITWIN_TREST_FILT(1,ifilt_obs) ) .or.
     &           (Trest > FITWIN_TREST_FILT(2,ifilt_obs) )
              REJECT_MJD =
     &          (MJD < FITWIN_MJD(1)) .or. (MJD > FITWIN_MJD(2))

              REJECT_DELCHI2  = (delchi2_nofudge  > DELCHI2_REJECT  )
              REJECT_SIGNOISE = (signoise_data < SIGNOISE_REJECT)

              LREJECT  =
     &              REJECT_DELCHI2 .or. REJECT_SIGNOISE .or.
     &              REJECT_TREST   .or. REJECT_MJD

              LREJECT2  =
     &            (REJECT_DELCHI2 .or. REJECT_SIGNOISE) .and.
     &            (.not. REJECT_TREST )

              if ( epoch < MXFIT_DATA ) then
                I4EP_ALL(epoch,IEP_REJECT)  = 0
                I4EP_ALL(epoch,IEP_REJECT2) = 0
                if ( LREJECT  ) I4EP_ALL(epoch,IEP_REJECT)  = 1
                if ( LREJECT2 ) I4EP_ALL(epoch,IEP_REJECT2) = 1  ! Mar 2020
              endif

           endif  ! end FIRST_ITERATION

           if ( LFITDATA .and. (.NOT.LFLAG_USESIM) ) then

             FCN_FITCHI2(ifilt)  =
     &       FCN_FITCHI2(ifilt)  + sqdif / sqsig_nofudge  ! DELCHI2

             if ( Trest .LT. R4SN_Tearly ) R4SN_Tearly = Trest
             if ( Trest .GT. R4SN_Tlate  ) R4SN_Tlate  = Trest

             if ( MJD .LT. R4SN_MJDmin ) R4SN_MJDmin = MJD
             if ( MJD .GT. R4SN_MJDmax ) R4SN_MJDmax = MJD

             ! sums used for initializing photoz x0/MU
             if ( LFLAG_USER .and. SNR_RAW > 3.0 .and.
     &            ISCALE_COURSEBIN_PHOTOZ > 0 ) then
                R4SN_FFSUM_DATA   = R4SN_FFSUM_DATA
     &               + (flux_data**2)*inv_sqsig
                R4SN_FFSUM_MODEL  = R4SN_FFSUM_MODEL
     &               + (flux_model**2)*inv_sqsig
                R4SN_FFSUM_CROSS  = R4SN_FFSUM_CROSS
     &               + (flux_data*flux_model)*inv_sqsig


             endif

           endif

        ENDIF  ! end of LAST if-block

102   CONTINUE  ! end of IFITDATA loop

c -----------------------

c check DUMP flags.

      IF ( NDMPFCN(0) .GT. 0 ) THEN

        star = ' '
        if ( LREPEAT_ITER ) star = '*'

        DO ifilt = 1, MXFILT_OBS

          LTMP = NFITDATA_FILT(ifilt)>0 .and. NDMPFCN(ifilt).GT.0
          IF ( LTMP ) THEN
            ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
            cfilt     = filtdef_string(ifilt_obs:ifilt_obs)

           write(6,672) ITER, star
     &          ,NEPOCH_ALL(ifilt)
     &          ,NEPOCH_REJECT(ifilt)
     &          ,cfilt, chi2filt(ifilt)
     &          ,chi2filt_sigma(ifilt)

672        format(T3, 'ITER=',I1,A, '  NEPOCH=',I3,'-',I2,' : ',
     &         'CHI2-TOT(',A1,')=', G10.5, 2x ,
     &         'CHI2(SIGMA)=', G12.3 )

          ENDIF
        ENDDO
        print*,'   CHI2-TOT(all filters) = ', chi2
        print*,'      ********* END OF FCN DUMP ********** '
        CALL FLUSH(6)
      ENDIF

c ----------------------------------

      IF ( LFLAG_SIGMA_ONLY ) RETURN
      IF ( LFLAG_USESIM     ) RETURN

c ----------------------
c compute chi2 from covariance matrix

      IF ( USE_FITCOV ) THEN
        chi2    = CHI2INI + chi2sum_sigma

c  check option to re-compute covariance inside minuit function
        if ( OPT_COVAR_FLUX .EQ. 2 ) then
           DO ipar = 1, NFITPAR_MN
             XVAL4COV(ipar) = XVAL(ipar)  ! used for COV opt
           ENDDO

c    modify x1 for SALT2 model.
           if  ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
             x1 = XVAL4COV(IPAR_SHAPE)
             XVAL4COV(IPAR_SHAPE)  = SALT2xx1(ITER,x1)
           endif

c  re-compute COVARIANCE and its inverse => COVMAT2
c  1st arg OPT=0 suppresses printing.
           CALL FITINI_COV(0,iter,XVAL4COV,IERR)
        endif

c loop over COV_INV elements and compute chi2

        DO 801 irow = 1,    NFITDATA
        DO 802 icol = irow, NFITDATA
           COV_INV  = covmat2(irow,icol)
           if ( COV_INV .EQ. 0.0 ) GOTO 802

           FF   = del_flux(irow) * del_flux(icol)
           if ( irow .EQ. icol ) then
              chi2 = chi2 + (FF * COV_INV)
           else
              chi2 = chi2 + (FF * COV_INV * 2.)  ! include ij + ji terms
           endif

c   check option to include log[det(COV_INC)] term
ccc xxx not yet ...  chi2 = chi2 - log(DETERM_COVMAT2)

802     CONTINUE
801     CONTINUE


        FCN_FITCHI2(0) = chi2 - chi2ini

      ENDIF  ! end of LFLAG_COVAR loop

      RETURN
      END  ! FCNSNLC


C ==============================================================
CDECK  ID>,  FCNCHI2_PRIOR. 
      DOUBLE PRECISION FUNCTION FCNCHI2_PRIOR(XVAL,CHI2PRIOR)
c
c Created Apr 03, 2009 by R.Kessler
c Evaluate prior-chi2 and return total prior-chi2.
c
c Apr 3 2018: include color-prior chi2
c
c Jun 2022: check option to use zphot quantiles
c Jan 2024: check prior for IPAR_SHAPE2 (2nd SHAPE param)
c
c --------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c function args
      REAL*8
     &   XVAL(MXFITPAR)         ! (I) fit parameters
     &  ,CHI2PRIOR(0:MXFITPAR)  ! (O) prior-chi2 for SEEFF & each parameter

c local args

      INTEGER  IPAR, ISN, IERR, IPAR_DIST, q

      REAL*8
     &   CHI2INI, CHI2TMP
     &  ,COLOR, COLORMAX, RV, SHAPE(2), PEAKMJD, DIST, MU, ZSN
     &  ,arg_tmp, DIF, pull, EFF, SQSIG, PROBZ

      LOGICAL LTMP, LBADVAL, DO_QUANTILES, DO_BESTZ_GAUSS

c define max color and MU for which exponential priorchi2 is used
c to prevent MINUIT from probing extreme values.

      REAL*8  CMAX_SALT2, AVMAX, MUMIN, MUMAX
      PARAMETER (
     &   CMAX_SALT2 = 0.5  ! max abs(color) for SALT2
     &  ,AVMAX      = 5.0  ! max AV for host-galaxy extinction
     &  ,MUMIN      = 10.  ! min dist mod
     &  ,MUMAX      = 60.  ! max distance mod.
     &     )

c functions
      REAL*8
     &   CHI2_PRIOR
     &  ,PRIOR_ZPULL
     &  ,PRIOR_MUPULL
     &  ,GET_RV8
     &  ,SNLC_FIT_SIMEFF
     &  ,eval_zPDF_spline

      EXTERNAL eval_zPDF_spline

c ------------- BEGIN --------------


c init output
      FCNCHI2_PRIOR = 0.0
      LBADVAL = .FALSE.

c init CHI2PRIOR and check for crazy fit params

      CHI2PRIOR(0) = 0.0
      DO 100 IPAR = 1, MXFITPAR
         CHI2PRIOR(ipar) = 0.0

         IF ( IPAR .EQ. IPAR_ITER ) GOTO 100
         IF ( IPAR .EQ. IPAR_ISN  ) GOTO 100

c check for NANs
         LTMP = XVAL(ipar) .GE. INIBND(1,ipar)
     &    .and. XVAL(ipar) .LE. INIBND(2,ipar)

         if ( .NOT. LTMP ) then
            CHI2PRIOR(ipar) = 1.111E9
            LBADVAL = .TRUE.
         endif
100   CONTINUE

      if ( LBADVAL ) goto 888

c strip off XVAL parameters into local variables.

      ISN        = int ( XVAL(IPAR_ISN) )
      COLOR      = XVAL(IPAR_AV)       !  AV or c
      RV         = GET_RV8(XVAL)
      SHAPE(1)   = XVAL(IPAR_SHAPE)
      SHAPE(2)   = XVAL(IPAR_SHAPE2)
      PEAKMJD    = XVAL(IPAR_PEAKMJD)
      DIST       = XVAL(IPAR_DLMAG)    ! MU or x0
      ZSN        = XVAL(IPAR_zPHOT)


      IF ( PARNAME_STORE(IPAR_DLMAG) .EQ. 'DLMAG' ) THEN
         MU = DIST
         COLORMAX = AVMAX
      ELSE

c translate SALT2 params into distance modulus
         MU = 30.0 - 2.5*log10(DIST)
     &      + (SALT2alpha*SHAPE(1)) - (SALT2beta * COLOR)

         COLORMAX = CMAX_SALT2
      ENDIF


c priors for all models to protect against crazy MINUIT excursions

      DIF     = PEAKMJD  - INIVAL(IPAR_PEAKMJD)
      CHI2PRIOR(IPAR_PEAKMJD)
     &        = CHI2_PRIOR(ipar_PEAKMJD,DIF)

c protect against crazy COLOR values
      if ( abs(COLOR) .GT. COLORMAX ) then
          DIF     = abs(COLOR) - COLORMAX
          arg_tmp = 0.5 * (DIF * DIF)
          CHI2PRIOR(IPAR_AV) = dexp(arg_tmp) - 1.0
      endif


c protect against against absurdly small & large distances
c (because MINUIT sometimes tries really crazy values)

      IPAR_DIST = IPAR_DLMAG  ! MU or x0

      if ( MU .LT. MUMIN ) then
         DIF     = MUMIN - MU
         arg_tmp = 0.5 * (DIF*DIF)
         CHI2PRIOR(IPAR_DIST) = dexp(arg_tmp) - 1.0
      endif
      if ( MU .GT. MUMAX ) then
         DIF     = MU - MUMAX
         arg_tmp = 0.5 * (DIF*DIF)
         CHI2PRIOR(IPAR_DIST) = dexp(arg_tmp) - 1.0
      endif

      IF ( OPT_PRIOR .EQ. 0 ) GOTO 888

c avoid crazy redshift value
      if ( ZSN .LT. Zat10pc ) then
          CHI2PRIOR(IPAR_zPHOT) = 1.0E8
          GOTO 888
      endif


c -----------------------------------------
c Prior on photoZ

      IF ( DOFIT_PHOTOZ ) THEN

c  load local variables for user-specified options from &SNLCINP OPT_PHOTOZ
        DO_QUANTILES    = btest(MASK_PHOTOZ_SOURCE,BIT_PHOTOZ_QUANTILES)
c xxx mark DO_BESTZ_GAUSS  = btest(MASK_PHOTOZ_SOURCE,BIT_BESTZ_GAUSS)

        if ( DO_QUANTILES ) then
          ! get the probability at this redshift
          PROBZ = eval_zPDF_spline(ZSN)  ! use zPDF from quantiles
          if ( PROBZ .le. 0. ) PROBZ = 1.0E-20
          CHI2PRIOR(IPAR_zPHOT) = -2.0*DLOG( PROBZ )
        else
          pull   = PRIOR_ZPULL(ZSN)
          CHI2PRIOR(IPAR_zPHOT) = CHI2_PRIOR(ipar_zPHOT,pull)
        endif

        if ( DEBUG_FLAG == 908 ) then
           CALL DUMP_ZPHOT_PRIOR(ZSN,PROBZ)
        endif
        pull   = PRIOR_MUPULL(isn,ZSN,MU)
        CHI2PRIOR(IPAR_DLMAG) = CHI2PRIOR(IPAR_DLMAG) +
     &  CHI2_PRIOR(ipar_DLMAG,pull)

      ENDIF

c -------------------------
c prior on shape
      CHI2PRIOR(IPAR_SHAPE)
     &          = CHI2_PRIOR(IPAR_SHAPE,SHAPE(1))

c prior on 2nd shape par
      IF ( NSHAPEPAR > 1 ) THEN
        CHI2PRIOR(IPAR_SHAPE2)
     &          = CHI2_PRIOR(IPAR_SHAPE2,SHAPE(2))

c        print*,' xxx x2, chi2prior = ', sngl(SHAPE(2)),
c     &        sngl(CHI2PRIOR(IPAR_SHAPE2))
      ENDIF

c ----------------------
c prior on SALT2 color (Apr 2018)

      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
        CHI2PRIOR(IPAR_COLOR)
     &          = CHI2_PRIOR(IPAR_COLOR,COLOR)
      ENDIF

c ----------------------------------------------
c Jul 25, 2011: prior for simulated efficiency

      IF ( OPT_PRIOR_SIMEFF .GT. 0  ) THEN
         EFF = SNLC_FIT_SIMEFF(ISN,XVAL)
         CHI2PRIOR(0) = -2.0*DLOG( EFF )
      ENDIF


c =================================================
      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) GOTO 888 ! restore 6/19/23
cc      IF ( LOBS_FITMODEL ) GOTO 888  ! xxx mark delete Jun 19 2023
c =================================================

c Prior on AV
      IF ( INISTP_AV .NE. 0.0 ) then
        CHI2PRIOR(IPAR_AV)
     &          = CHI2_PRIOR(ipar_av,COLOR)

        CHI2PRIOR(IPAR_RV)
     &          = CHI2_PRIOR(ipar_rv,XVAL(IPAR_RV) )
      ENDIF


888   CONTINUE
c sum all the pieces
      DO IPAR = 0, MXFITPAR
         FCNCHI2_PRIOR = FCNCHI2_PRIOR + CHI2PRIOR(ipar)
      ENDDO

      RETURN
      END  ! end FCNCHI2_PRIOR

C ==============================================
CDECK  ID>,  DUMP_ZPHOT_PRIOR. 
      SUBROUTINE DUMP_ZPHOT_PRIOR(ZSN,PROBZ)
c --------------------
c Created Sep 8, 2022
c R. Chen
c Debug photo-z prior information
c --------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
      REAL*8 ZSN,PROBZ
      REAL*8 CHI2PRIOR_ORIG,CHI2PRIOR_CALC,CHI2PRIOR_QUANTILE
      REAL*8 pull,sig,CHI2_LOGSIG
      REAL*8 PRIOR_ZPULL,CHI2_PRIOR
      LOGICAL USE_Q
c BEGIN
      USE_Q = btest(OPT_PHOTOZ,BIT_PHOTOZ_QUANTILES)
      sig = SNHOST_ZPHOT_ERR(1)
      CHI2_LOGSIG = DLOG(2.0*3.14159*sig*sig)
      CHI2_LOGSIG = 0
      CHI2PRIOR_CALC = ((ZSN - SNHOST_ZPHOT(1))/sig)**2 + CHI2_LOGSIG
      if (USE_Q) then
        CHI2PRIOR_QUANTILE = -2.0*DLOG( PROBZ )
        CHI2PRIOR_ORIG = -9
      else
        CHI2PRIOR_QUANTILE = -9
        pull   = PRIOR_ZPULL(ZSN)
        CHI2PRIOR_ORIG = CHI2_PRIOR(ipar_zPHOT,pull) + CHI2_LOGSIG
      endif

      write(6,40) ZSN,sig,PROBZ,CHI2PRIOR_ORIG,CHI2PRIOR_CALC,
     & CHI2PRIOR_QUANTILE
40    format(' z=',F5.3, 3x,'sigz=',F5.3, 3x,'PROBZ= ',F5.3,3x,
     & 'CHI2zPRIOR[ORIG,CALC,Q] = ' , 3F10.4)
      CALL flush(6)
      RETURN
      END

C ==============================================
CDECK  ID>,  FCNCHISIG. 
      DOUBLE PRECISION FUNCTION FCNCHI2_SIGMA(iter,iepoch,fluxerr)

c --------------------------
c Created April 23, 2011
c [moved code out of FCNSNLC to clean up and fix bug]
c
c Return chi2 contribution from error-term, relatiave to last interation.
c The nominal term is -2ln(FLUXERR) but instead here we compute
c
c      FCNCHI2_SIGMA = -2ln(FLUXERR/LAST_FLUXERR)
c
c so that this is nominally ~zero if the flux-error does not
c change much between iterations.
c
c Also fix bug by returning zero if 1st-iteration FLUXERR=0 ...
c this can happen if a new filter is added in the 2nd iteration.
c
c Aug 22, 2011: allow CHI2_SIGMA calc if OPT_COVAR_FLUX > 0
c Jan 25, 2014:
c   * use new R4EP_LAST array
c   * pass iepoch instead of ifitdata
c
c ------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )




c +CDE,SNANAFIT.

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c function args
      INTEGER
     &   ITER         ! (I) fit iteration
     &  ,IEPOCH       ! (I) index to R4EP arrays

      REAL*8 FLUXERR ! (I) error on flux

c local args

      INTEGER IFILT_OBS
      REAL*8  SIGRAT, LAST_FLUXERR
      CHARACTER CFILT*2

c function
      LOGICAL FIRST_ITERATION

c ----------- BEGIN -----------

      FCNCHI2_SIGMA = 0.0               ! init to zero chi2
      IF ( FIRST_ITERATION(ITER) ) RETURN
      IF ( .NOT. DOCHI2_SIGMA    ) RETURN  ! check user option

      LAST_FLUXERR = DBLE( R4EP_LAST(iepoch,JEP_FLUX_ERRTOT) )

      if ( LAST_FLUXERR .LE. 1.0E-11 ) RETURN

c      ifilt_obs = I4EP_ALL(iepoch,IEP_IFILT_OBS)  ! for debug only
c      cfilt     = filtdef_string(ifilt_obs:ifilt_obs) ! for debug only

      SIGRAT = FLUXERR/LAST_FLUXERR
      FCNCHI2_SIGMA = 2.*dlog(sigrat)

      RETURN
      END

C ==============================================
CDECK  ID>,  USRFUN. 
      DOUBLE PRECISION FUNCTION USRFUN (
     &   ITER        ! (I) fit iteration used for parm-dependent error calc
     &  ,IFILT_OBS   ! (I) index of observer -filter
     &  ,ZSN         ! (I) redshift
     &  ,Tobs        ! (I) T - Tpeak, observer frame
     &  ,SHAPE       ! (I) shape-par (DELTA, STRETCH, ETC ... )
     &  ,DIST        ! (I) MU=5*LOG10(10pc/DL) or x0
     &  ,AVHOST      ! (I) extinction in SN host galaxy (not used)
     &  ,RVHOST      ! (I) RV in SN host gal (not used)
     &  ,MWEBV       ! (I) local MW extinction (add 1/25/2007)
     &  ,LDMP        ! (I) dump-option
     &  ,AVwarp      ! (O) "AV" used to warp spectral template
     &  ,mag_kcor    ! (O) K-correction & error used
     &  ,mag_xtav    ! (O) host-gal extinction in rest-frame filter
     &  ,mag_xtmw    ! (O) MW extinction on obs-frame filter
     &  ,mag_err     ! (O) mag-error from model
     &    )

c ----------------------------------------------------
c  Returns predicted Flux based on input parameters.
c
c
c Jan 16, 2012: fix long-standing patchy bug NOAVWARP;
c               test-code had always been included,
c               thus blowing up the errors.
c
c Jul 2013: change name of MU argument to DIST
c
c Sep 22 2013: add args RV and OPT_MWCOLORLAW to get_mwxt8().
c
c Mar 19 2018: call SALT2zz to get redshift used in error calc.
c              Goal is to remove photo-z pathologies.
c
c ----------------------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT.  PARNAME_STORE is here inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP.  NFIT_ITERATION is here inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

cc      DOUBLE PRECISION USRFUN

c function args

      INTEGER ITER, IFILT_OBS  ! (I)

      DOUBLE PRECISION
     &   ZSN, Tobs, SHAPE(2), DIST        ! (I)
     &  ,AVHOST, RVHOST, MWEBV            ! (I)
     &  ,AVWARP, MAG_KCOR(2)              ! (O)
     &  ,MAG_XTAV, MAG_XTMW, MAG_ERR      ! (O)

c local args

      DOUBLE PRECISION
     &   Z1, Z0
     &  ,Trest
     &  ,MAG_REST(MXFILT_ALL)
     &  ,MAG_BESSELL_REST(MXFILT_ALL)
     &  ,MAG_BESSELL_OBS(MXFILT_ALL)
     &  ,MAG_LANDOLT_REST(MXFILT_ALL)
     &  ,MAG_LANDOLT_OBS(MXFILT_ALL)
     &  ,MAGERR_REST(MXFILT_ALL)
     &  ,MAGERR_OBS_TMP(MXFILT_ALL)
     &  ,MAG_XTAV_REST(MXFILT_ALL)
     &  ,MAG_XTMW_OBS(MXFILT_ALL)
     &  ,KCOR_TMP(MXFILT_ALL)
     &  ,KCORERR_TMP(MXFILT_ALL)
     &  ,KCOR_NOAVWARP(MXFILT_ALL)
     &  ,AVWARP_TMP(MXFILT_ALL)
     &  ,MAG_OBS_TMP(MXFILT_ALL)
     &  ,MAG_TMP1, MAG_TMP2, MWXT_TMP
     &  ,SQMAGERR, MAGERR_KCOR
     &  ,MAG_COR, MAG_PEAK, MAG_OBS
     &  ,FLUX, ARG, MJD, XT
     &  ,STR1, STR2, DELTA, DM15
     &  ,BX_synth, B_synth
     &  ,SALT2x0, SALT2x1, xx1, SALT2c, zz, RVDUM, AVDUM
     &  ,AVMW, LAMAVG, LAMREST, WGT1, WGT2
     &  ,LAMDIF12, LAMDIF13, DIF
     &  ,ERRTMP1, ERRTMP2
     &  ,MUTMP, MWEBV_MODEL, RVMW

      INTEGER
     &   istat
     &  ,ifilt
     &  ,ifilt_rest
     &  ,ifilt_rest1
     &  ,ifilt_rest2
     &  ,ifilt_rest3
     &  ,ifilt_rest_tmp(3)
     &  ,ifilt_tmp
     &  ,ifilt2
     &  ,ifilt2_obs
     &  ,Nepoch
     &  ,VBOSE
     &  ,LL, LPAR_SHAPE, LPAR_COLOR, LPAR_X0
     &  ,OPT, inear
     &  ,ISN, CID
     &  ,NFILT_FITMAP_REST
     &  ,IFILT_FITMAP_REST(MXFILT_OBS)
     &  ,MSKTMP, NFTMP
     &  ,MSKSALT2, MSKBAYESN

      INTEGER*8 MSKFILT8(2), MSKTMP8(2)

      CHARACTER CFILT*2, CTMP2*2, CCID*(MXCHAR_CCID)
      REAL*4 Z4, LAMDIF4(3)

c KCORFUN8 args
      INTEGER IFILT_REST_KCORFUN(3)
      REAL*8
     &    MAG_REST_KCORFUN(3)
     &   ,LAMDIF_KCORFUN(3)
     &   ,AVWARP_KCORFUN(3)

      LOGICAL
     &    LTMP
     &   ,LBESS_OBS, LSNXTAV, LSNXTMW, ISREST, ISOBS
     &   ,LDMP, NEEDU,  DOKCOR13, LCRAZYMAG, DOMBSALT2
     &   ,ABORT_ON_DMP

c functions
      INTEGER
     &   NEAREST_IFILTDEF_WRAPPER
     &  ,GENMAG_STRETCH2
     &  ,GENMAG_MLCS2K2
     &  ,GENMAG_SNOOPY
     &  ,LANDOLT_CONVERT
c     &  ,FILTINDX

      LOGICAL FILTBTEST

      REAL*8
     &   GET_MAGLC8
     &  ,GET_MWXT8     ! get MW extinct
     &  ,GET_SNXT8     ! get hostgal extinct
     &  ,genmag_extinction
     &  ,GET_AVWARP8   ! get AV needed to warp SN SED
     &  ,GET_KCORERR_LEGACY  ! get Kcor error
     &  ,eval_kcor_table_AVWARP  ! C code
     &  ,eval_kcor_table_LCMAG   ! C code
     &  ,eval_kcor_table_MWXT   ! C code
     &  ,GET_KCOR_DRIVER        ! C code
     &  ,GET_KCORERR            ! C code
     &  ,GALextinct    ! returns approx MW extinction
     &  ,KCORFUN8
     &  ,DLMAG8_REF
     &  ,SALT2x0calc, SALT2xx1, SALT2zz, SALT2x2
     &  ,PARLIST_SN(10), PARLIST_HOST(10)

c ------------- BEGIN ------------

c init output args
      AVWARP       = NULLVAL
      MAG_KCOR(1)  = NULLVAL
      MAG_KCOR(2)  = NULLVAL
      mag_xtav     = NULLVAL
      mag_xtmw     = NULLVAL
      mag_err      = NULLVAL
c -----------------

      ABORT_ON_DMP = .FALSE.

      USRFUN   = 1.0
      Nepoch   = 1     ! 1 epoch
      VBOSE    = 0

      Z0      = Zat10pc
      Z1      = 1.0 + ZSN
      Trest   = Tobs / Z1
      RVMW    = DBLE(RV_MWCOLORLAW)

c check for special case where IFILT_OBS is really a rest-filter
      IF ( ZSN .LT. Z0*1.001 ) then
        ISREST = .TRUE.
      ELSE
        ISREST = .FALSE.
      ENDIF

      IF ( ISREST ) THEN
        LAMAVG  = DBLE( FILTREST_LAMAVG(ifilt_obs) )
        LAMREST = DBLE( FILTREST_LAMAVG(ifilt_obs) )
      ELSE
        LAMAVG  = DBLE( FILTOBS_LAMAVG(ifilt_obs) )
        LAMREST = DBLE( FILTOBS_LAMAVG(ifilt_obs) ) / Z1
      ENDIF

      NFILT_FITMAP_REST    = 0

      MWEBV_MODEL = MWEBV
      IF ( USE_MWCOR ) MWEBV_MODEL = 0.0 ! data already corrected

      LBESS_OBS = IFILT_OBS .GE. IFILT_BESS_U .and.
     &            IFILT_OBS .LE. IFILT_BESS_I

c get approx MW extinction (for printout only ... not for calculation)
      AVMW     = RVMW * mwebv_model ;
      MAG_XTMW = GALextinct ( RVMW, AVMW, LAMAVG, 94 );

c if we have observer-frame model, then skip all
c the rest-frame stuff.

      IF ( LOBS_FITMODEL ) GOTO 333

c get nearest and 2nd nearest filter in rest frame.
c Note that IFILT_REST1[2] are absolute (NOT sparse) filter indices.

      IF ( ISREST ) then
        OPT = OPT_FILTREST
      ELSE
        OPT = OPT_FILTOBS
      ENDIF
      Z4  = sngl(ZSN)

      ifilt_rest1 =
     &  NEAREST_IFILTDEF_WRAPPER( opt, ifilt_obs, 1, Z4, LAMDIF4(1))
      ifilt_rest2 =
     &  NEAREST_IFILTDEF_WRAPPER( opt, ifilt_obs, 2, Z4, LAMDIF4(2))
      ifilt_rest3 =
     &  NEAREST_IFILTDEF_WRAPPER( opt, ifilt_obs, 3, Z4, LAMDIF4(3))

c check if KCOR13 (based on warping other neighbor) should be
c wgt-averaged with nominal KCOR12.
c First that order is 3-1-2  or  2-1-3.

      LAMDIF12 = DBLE(  FILTREST_LAMAVG(ifilt_rest2)
     &                - FILTREST_LAMAVG(ifilt_rest1) )
      LAMDIF13 = DBLE( FILTREST_LAMAVG(ifilt_rest1)
     &               - FILTREST_LAMAVG(ifilt_rest3) )
      DOKCOR13 = (LAMDIF12/LAMDIF13) .GT. 0.0

c xxxxxxxxxxxxxxxxxxxx mark delete xxxxxxxxxxx
c      print*,' xxx ------------------ '
c      write(6,3333) ifilt_rest1, ifilt_rest2, ifilt_rest3,
c     &      LAMDIF12, LAMDIF13
c3333  format(' xxx ifilt_rest[1,2,3]=',3I3, 2x,'LAMDIF[12,13]=',2F9.1)
c      call flush(6)
c xxxxxxxxxxxxxxxxxxxx

c update rest-frame map for photoZ fit (if IFILT is defined)

      if ( DOFIT_PHOTOZ ) then
          ifilt = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
          if ( ifilt .GT. 0 ) then
            IFILT_REST_MAP(ifilt) = ifilt_rest1
          endif
      endif

c check option for rest-frame mags only with no K-correction

      IF ( ISREST ) then
        NFILT_FITMAP_REST    = 1
        IFILT_FITMAP_REST(1) = IFILT_REST1
        IFILT_REST1          = IFILT_REST1
        IFILT_REST2          = IFILT_REST1
        IFILT_REST3          = IFILT_REST1
        GOTO 333
      ENDIF

      NEEDU = ifilt_rest1 .EQ. ifilt_BESS_U .or.
     &        ifilt_rest2 .EQ. ifilt_BESS_U

      NFILT_FITMAP_REST    = 2
      IFILT_FITMAP_REST(1) = ifilt_rest1
      IFILT_FITMAP_REST(2) = ifilt_rest2

      IF ( DOKCOR13 ) THEN
        NFILT_FITMAP_REST    = 3
        IFILT_FITMAP_REST(3) = ifilt_rest3
      ELSE
        ifilt_rest3 = -9
      ENDIF

c xxxxxxxxxxxxxxxxxx mark delete xxxxxxxxx
c      print*,' xxx DOKCOR13, NEEDU = ', DOKCOR13, NEEDU
c      print*,' xxx NFILT_FITMAP_REST = ', NFILT_FITMAP_REST
c      print*,' xxx IFILT_FITMAP_REST = ', IFILT_FITMAP_REST(1:3)
c      call flush(6)
c xxxxxxxxxxxxxxxxxxxx

c expand filter ranges if Landolt option is set.

      IF ( USE_LANDOLT_REST  ) THEN

         NFILT_FITMAP_REST = 0
         do ifilt = 1, NFILTDEF_REST
            ifilt_rest = IFILTDEF_MAP_REST(ifilt)
            if ( ifilt_rest .NE. IFILT_BESS_BX ) then
              NFILT_FITMAP_REST = NFILT_FITMAP_REST + 1
              IFILT_FITMAP_REST(ifilt) = ifilt_rest
            endif

         enddo

      ENDIF

c init filter-dependent variables.

333   CONTINUE

      DO ifilt = 1, MXFILT_ALL
         MAG_REST(ifilt)         = 0.0
         MAGERR_REST(ifilt)      = 0.0
         MAG_XTAV_REST(ifilt)    = 0.0
         KCOR_TMP(ifilt)         = 0.0
         KCORERR_TMP(ifilt)      = 0.0
         MAG_XTMW_OBS(ifilt)     = 0.0
         MAG_OBS_TMP(ifilt)      = 0.0
         MAG_LANDOLT_REST(ifilt) = 0.0
         MAG_LANDOLT_OBS(ifilt)  = 0.0
         MAG_BESSELL_REST(ifilt) = 0.0
         MAG_BESSELL_OBS(ifilt)  = 0.0
         AVwarp_tmp(ifilt)       = 0.0
      ENDDO

c -------------------------------------------
c get MAG_REST1 = magnitude in rest frame for closest filter
c     MAG_REST1 = mag in rest-frame for 2nd closest filter (for color)
c Use "genmag_xxx" function that are used in simulation.

      IF ( FITMODEL_INDEX .EQ. MODEL_STRETCH ) THEN

         STR1       = SHAPE(1)
         STR2       = STR1

         do ifilt = 1, NFILT_FITMAP_REST
            IFILT_REST = IFILT_FITMAP_REST(ifilt)

c return MAG_REST
            istat = genmag_stretch2 (
     &           STR1, STR2, IFILT_REST, Nepoch, Trest    ! input
     &         , MAG_REST(ifilt_rest)          ! (O)
     &         , MAGERR_REST(ifilt_rest) )     ! (O)
         enddo

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_STRETCH2 ) THEN

         STR1       = SHAPE(1)
         STR2       = SHAPE(2)

         do ifilt = 1, NFILT_FITMAP_REST
            IFILT_REST = IFILT_FITMAP_REST(ifilt)

c return MAG_REST
            istat = genmag_stretch2 (
     &           STR1, STR2, IFILT_REST, Nepoch, Trest   ! input
     &         , MAG_REST(ifilt_rest)       ! (O)
     &         , MAGERR_REST(ifilt_rest) )  ! (O)

         enddo

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_MLCS2k2 ) THEN

          DELTA  = SHAPE(1)

         do ifilt       = 1, NFILT_FITMAP_REST
             IFILT_REST = IFILT_FITMAP_REST(ifilt)

c note that genmag_mlcs starts at 0, so subtract 1 from index.
             ifilt_tmp  = IFILTINVMAP_MODEL(ifilt_rest) - 1
             if ( ifilt_tmp < 0 ) then
               c1err = 'Invalid rest-frame filt for genmag_mlcs2k2: '//
     &               FILTDEF_STRING(IFILT_REST:IFILT_REST)
               c2err = 'Valid rest-frame filters: ' //
     &               FILTLIST_MODEL(1:NFILT_MODEL)
               CALL MADABORT("USRFUN", c1err, c2err )
             endif

             istat = genmag_mlcs2k2(
     &              ifilt_tmp, DELTA, Nepoch, Trest  ! (I)
     &            , MAG_REST(ifilt_rest)       ! (O)
     &            , MAGERR_REST(ifilt_rest) )  ! (O)

          enddo

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SNOOPY ) THEN

         DM15     = SHAPE(1)

         do ifilt = 1, NFILT_FITMAP_REST
            IFILT_REST = IFILT_FITMAP_REST(ifilt)
            ifilt_tmp  = IFILTINVMAP_MODEL(ifilt_rest) - 1  ! C index

            if ( ifilt_tmp < 0 ) then
               c1err = 'Invalid rest-frame filter for genmag_snoopy: '//
     &               FILTDEF_STRING(IFILT_REST:IFILT_REST)
               c2err = 'Valid rest-frame filters: ' //
     &               FILTLIST_MODEL(1:NFILT_MODEL)
               CALL MADABORT("USRFUN", c1err, c2err )
            endif

            istat = genmag_snoopy(ifilt_tmp, DM15, Nepoch, Trest
     &            ,MAG_REST(ifilt_rest)       ! (O)
     &            ,MAGERR_REST(ifilt_rest) )  ! (O)

          enddo

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN

          MSKSALT2  = 0   ! bit0 => nominal, return flux
          SALT2x1 = SHAPE(1)
          SALT2x2 = SHAPE(2)    ! Dec 2023
          SALT2c  = AVHOST
          xx1     = SALT2xx1(ITER,SALT2x1)  ! x1 used in model-err calc
          zz      = SALT2zz(ITER,ZSN)       ! z  used in model-err calc

c translate fit-params into SALT2 language

          if ( OPT_SALT2FIT .EQ. 0  ) then  ! default
             SALT2x0 = DIST

          else if ( OPT_SALT2FIT .EQ. 1  ) then
             SALT2x0 = TEN8**DIST    ! MU

          else if ( OPT_SALT2FIT .EQ. 2  ) then
             MUTMP = (DIST + DLMAG8_REF(ZSN))   ! DIST is really MUDIF
             SALT2x0 = SALT2x0calc(ZERO8,ZERO8, ZERO8, ZERO8, MUTMP )

          else if ( OPT_SALT2FIT .EQ. 4  ) then  ! emulate Julien/snfit
             SALT2x0 = DIST      ! same as for default
             if ( ITER .LE. 2 ) then
                MSKSALT2 = 4     ! set errors to zero
                xx1      = 0.0   ! redundant
             endif
          endif

          MSKFILT8(1) = IFILT_OBS_EVAL_MASK(1,ifilt_obs)
          MSKFILT8(2) = IFILT_OBS_EVAL_MASK(2,ifilt_obs)

          NFTMP = NFILTDEF_SURVEY

c loop over all needed obs-filters;
c multiple filters are needed for Landolot color transf.

          RVDUM = 0.0 ; AVDUM=0.0  ! cannot fit for Mandel's extinc params
          PARLIST_SN(1) = SALT2x0
          PARLIST_SN(2) = SALT2x1
          PARLIST_SN(3) = SALT2c
          PARLIST_SN(4) = xx1
          PARLIST_SN(5) = SALT2x2
          PARLIST_HOST(1) = RVDUM
          PARLIST_HOST(2) = AVDUM
          PARLIST_HOST(3) = -9.0   ! logMass

          DO ifilt2 = 1, NFTMP
             ifilt2_obs = IFILTDEF_MAP_SURVEY(ifilt2)
             mag_obs_tmp(ifilt2_obs) = 0.0
             LTMP = FILTBTEST(MSKFILT8,ifilt2_obs)
             if ( LTMP ) then
               CALL genmag_salt2( MSKSALT2, ifilt2_obs
     &          , PARLIST_SN, PARLIST_HOST, MWEBV_MODEL
     &          , ZSN, ZZ, Nepoch, Tobs
     &          , MAG_OBS_TMP(ifilt2_obs)       ! return arg
     &          , MAGERR_OBS_TMP(ifilt2_obs)  ) ! return arg

             endif
          ENDDO  ! ifilt2 loop


c mag error is from the nominal filter ... ignore mag_err
c from other filters used for Landolt color trans.

          MAG_ERR = MAGERR_OBS_TMP(ifilt_obs)

          GOTO 501  ! skip K-corrections and other rest-frame stuff

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_BAYESN ) THEN

          MSKBAYESN = 0
          PARLIST_SN(1) = DIST      ! distance modulus
          PARLIST_SN(2) = SHAPE(1)  ! THETA
          PARLIST_SN(3) = AVHOST    ! host extiction
          PARLIST_SN(4) = RVHOST    ! RV for host

          CALL genmag_BAYESN( MSKBAYESN, ifilt_obs
     &          , PARLIST_SN, MWEBV_MODEL
     &          , ZSN, Nepoch, Tobs
     &          , MAG_OBS_TMP(ifilt_obs)       ! return arg
     &          , MAG_ERR                    ) ! return arg

          GOTO 501  ! skip K-corrections and other rest-frame stuff

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SIMSED ) THEN

c translate fit-params into SALT2 language

          MUTMP   = (DIST + DLMAG8_REF(ZSN))   ! DIST is really MUDIF
          SALT2x0 = TEN8** (-0.4*MUTMP )      ! borrow SALT2x0 for now

          SALT2x1 = 0.0  ! unused shape-par variable for SIMSED

          MSKTMP  = 1  ! bit0 => return flux instead of mag
c xxxxxxx
c          CALL genmag_simsed( MSKTMP, ifilt_obs
c     &          , SALT2x0, SALT2x1
c     &          , MWEBV_MODEL, ZSN, Nepoch, Tobs
c     &          , flux, mag_err )  ! returns FLUX and MAG_ERR
c xxxxxxx
          GOTO 502  ! skip K-corrections and other rest-frame stuff

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_FIXMAG ) THEN


      ENDIF

c -----------------------------------
c check option for rest-frame mag only
c Include host extinction to get rest-frame colors.

      IF ( ISREST ) THEN

        XT = genmag_extinction(ifilt_obs, Trest, RVHOST, AVHOST)
        MAG_XTAV_REST(ifilt_obs) = XT

        MAG_OBS_TMP(ifilt_obs) =
     &  MAG_REST(IFILT_OBS) + MAG_XTAV_REST(ifilt_obs)

        GOTO 777  ! skip K-corr and extinction
      ENDIF

c check for option to smooth rest-frame model
c across filter boundaries

      IF ( LREST_FITMODEL ) THEN

         CALL RESTFILT_WGT(LAMREST, ifilt_rest1, ifilt_rest2,   ! (I)
     &             WGT1, WGT2) ! (O) return wgts (sum to 1)

         ERRTMP1 = MAGERR_REST(ifilt_rest1)
         ERRTMP2 = MAGERR_REST(ifilt_rest2)

c smooth the errors
         MAGERR_REST(ifilt_rest1) = WGT1*ERRTMP1 + WGT2*ERRTMP2
         MAGERR_REST(ifilt_rest2) = WGT1*ERRTMP2 + WGT2*ERRTMP1

      ENDIF

c set temp arrays MAG_BESSELL and MAG_LANDOLT

      DO ifilt      = 1, NFILT_FITMAP_REST
         ifilt_rest = IFILT_FITMAP_REST(ifilt)
         MAG_BESSELL_REST(ifilt_rest) = MAG_REST(ifilt_rest)
         MAG_LANDOLT_REST(ifilt_rest) = MAG_REST(ifilt_rest)
      ENDDO  ! end of IFILT loop

c -----------------------------------------------------------
c If Landolt option is set, then assume MAG_REST is in Landolt system
c and convert to Bessell system before applying Kcor to observer frame.

      IF ( USE_LANDOLT_REST ) THEN  ! rest-frame conversions

c If U-band is needed (NEEDU), first get synthetic BX-B needed to
c convert Landolt-U back to synth Bessell.
c Store BX-B in the memory slot for Landolt-BX.

         MAG_LANDOLT_REST(IFILT_BESS_BX) = 0.0

         if ( NEEDU ) then

              AVWARP = EVAL_KCOR_TABLE_AVWARP(IFILT_REST1, IFILT_REST2,
     &              MAG_LANDOLT_REST(ifilt_rest1),
     &              MAG_LANDOLT_REST(ifilt_rest2),
     &              Trest, ISTAT)
              BX_synth = EVAL_KCOR_TABLE_LCMAG(ifilt_bess_BX, Trest,
     &                     Z0, AVwarp)
              B_synth  = EVAL_KCOR_TABLE_LCMAG(ifilt_bess_B, Trest,
     &                     Z0, AVwarp)

           MAG_LANDOLT_REST(IFILT_BESS_BX) = BX_synth - B_synth

         endif

c now convert to synthetic Bessell.

         opt   = -1   ! flag for Landolt -> Bessell conversion
         istat = Landolt_convert(opt
     &              ,MAG_LANDOLT_REST(IFILT_BESS_U)  ! input  UBVRI,BX-B
     &              ,MAG_BESSELL_REST(IFILT_BESS_U)  ! output UBVRI
     &                  )

         DO IFILT = 1,NFILT_FITMAP_REST
            IFILT_REST = IFILT_FITMAP_REST(ifilt)
            MAG_REST(ifilt_rest) = MAG_BESSELL_REST(ifilt_rest)
         ENDDO

c convert synthetic U into reported U by subtracting BX-B :
         MAG_REST(IFILT_BESS_U) = MAG_BESSELL_REST(IFILT_BESS_U)
     &                          - MAG_LANDOLT_REST(IFILT_BESS_BX)  ! -(BX-B)

         MAG_REST(ifilt_bess_BX) = MAG_REST(ifilt_bess_B)     ! B
     &                           + MAG_LANDOLT_REST(IFILT_BESS_BX) ! BX-B

      ENDIF  !  end of USE_LANDOLT_REST  if-block

c ----------------------------------------------------
c Now MAG_REST is in synthetic Bessell system;
c apply host extinction for rest-frame models.

      LSNXTAV = LREST_FITMODEL .and. AVHOST .NE. 0.0

      DO IFILT      = 1, NFILT_FITMAP_REST
         IFILT_REST = IFILT_FITMAP_REST(ifilt)

        IF ( LSNXTAV ) THEN

           XT = genmag_extinction(ifilt_rest, Trest, RVHOST, AVHOST)

           MAG_XTAV_REST(ifilt_rest) = XT

           MAG_REST(ifilt_rest) =
     &     MAG_REST(ifilt_rest) + MAG_XTAV_REST(ifilt_rest)

           MAG_BESSELL_REST(ifilt_rest) =
     &     MAG_BESSELL_REST(ifilt_rest) + MAG_XTAV_REST(ifilt_rest)

        ENDIF
      ENDDO

c --------------------------------------------
c determine K-correction; note that rest-frame mags
c include host-galaxy extinction.

      LSNXTMW = (ZSN .GT. 1.1 * Zat10pc) .and. (MWEBV .NE. 0.0)
      MSKTMP8(1) = IFILT_OBS_EVAL_MASK(1,ifilt_obs)
      MSKTMP8(2) = IFILT_OBS_EVAL_MASK(2,ifilt_obs)

      DO 155 ifilt2  = 1, NFILTDEF_SURVEY
         ifilt2_obs = IFILTDEF_MAP_SURVEY(ifilt2)

c check filter bit-mask to see if this IFILT needs to be evaluated.

        LTMP = FILTBTEST(MSKTMP8,ifilt2_obs)

        IF ( .not. LTMP ) goto 155

c get closest rest-frame filters for this observer "ifilt2_obs"
        OPT = OPT_FILTOBS
        DO inear = 1, 3
          ifilt_rest_tmp(inear) =
     &    NEAREST_IFILTDEF_WRAPPER(opt,ifilt2_obs,
     &                        inear,Z4,LAMDIF4(inear) )

c load KCORFUN8 args
          ifilt_tmp                 = ifilt_rest_tmp(inear)
          IFILT_REST_KCORFUN(inear) = ifilt_tmp
          MAG_REST_KCORFUN(inear)   = MAG_BESSELL_REST(ifilt_tmp)
          LAMDIF_KCORFUN(inear)     = DBLE( LAMDIF4(inear) )
        ENDDO

          KCOR_TMP(ifilt2_obs) =
     &    GET_KCOR_DRIVER(ifilt2_obs, IFILT_REST_KCORFUN,
     &            MAG_REST_KCORFUN,
     &            LAMDIF_KCORFUN, Trest, ZSN, AVWARP_KCORFUN )

c save AVwarp
        AVwarp                 = AVwarp_KCORFUN(2)
        AVwarp_tmp(ifilt2_obs) = AVwarp  ! save in case of dump

          ! refactored C code
        KCORERR_TMP(ifilt2_obs) =
     &      GET_KCORERR ( OPT_KCORERR, ifilt2_obs, ZSN )

        MAG_XTMW_OBS(ifilt2_obs) = 0.0
        if ( LSNXTMW ) then
           MWXT_TMP = EVAL_KCOR_TABLE_MWXT(ifilt2_obs, Trest, ZSN,
     &                    AVWARP, MWEBV, RVMW, OPT_MWCOLORLAW )
           MAG_XTMW_OBS(ifilt2_obs) = MWXT_TMP
        endif

c Add up all the pieces for observer mag prediction.

        MAG_OBS_TMP(ifilt2_obs) =
     &       MAG_BESSELL_REST(ifilt_rest_tmp(1)) ! rest-mag including host-AV
     &     + KCOR_TMP(ifilt2_obs)        ! K correction
     &     + DIST                        ! MU = 5*log10(10pc/DL)
     &     + MAG_XTMW_OBS(ifilt2_obs)    ! MilkyWay extinction

c xxxxxxxxxx mark delete Nov 28 2022 xxxxxx
c       write(6,6543) ifilt2_obs, MAG_BESSELL_REST(ifilt_rest_tmp(1)),
c     &        KCOR_TMP(ifilt2_obs), DIST, MAG_XTMW_OBS(ifilt2_obs)
c6543   format(' xxx ifilt2_obs=',I2, 2x, 'm_REST=',F7.3, 2x,
c     &         'kcor=',F7.3, 2x, 'D=',F7.3, 2x, 'mMW=',F7.3 )
c        call flush(6)
c xxxxxxxxxxxxxxxx end mark xxxxxxxxxxx

c check for option to subtract MWgalaxy extinction from model
c just like for the data.

        if ( USE_MWCOR ) then
          MAG_OBS_TMP(ifilt2_obs) =
     &    MAG_OBS_TMP(ifilt2_obs) - MAG_XTMW_REF(ifilt2_obs)
        endif

155   CONTINUE

c ---------------------------------------------
c load output args for function
c note that MAG_OBS is loaded below the 501-continue

777   CONTINUE
      AVwarp       = AVwarp_tmp(ifilt_obs)
      MAG_KCOR(1)  = KCOR_TMP(ifilt_obs)
      MAG_KCOR(2)  = KCORERR_TMP(ifilt_obs)
      MAGERR_KCOR  = KCORERR_TMP(ifilt_obs)
      MAG_XTAV     = MAG_XTAV_REST(ifilt_rest1)
      MAG_XTMW     = MAG_XTMW_OBS(ifilt_obs)

c determine model error as contribution from model and K-corr.

      SQMAGERR = 0.0
      IF ( USE_MODEL_MAGERR ) THEN
         SQMAGERR = MAGERR_REST(ifilt_rest1)**2 + MAGERR_KCOR**2
      ENDIF
      MAG_ERR = DSQRT(SQMAGERR)

c -------------------------------------

501   CONTINUE  ! come here when observer mag is calculate

c -------------------------------------------------
c if observer-frame is Bessell, and Landolt option is set,
c then transform observer-frame Bessell mags (MAG_BESSELL)
c to Landolt.

      IF ( USE_LANDOLT_OBS .and.
     &     LBESS_OBS       .and.
     &     .not. ISREST   ) THEN

c transfer MAG_OBS_TMP to temporary MAG_BESSELL_OBS array
c => input argument for LANDOLOT_CONVERT below.

         LCRAZYMAG = .FALSE.
         DO  ifilt2  = 1, NFILTDEF_SURVEY
           ifilt2_obs = IFILTDEF_MAP_SURVEY(ifilt2)
           if ( ifilt2_obs > 0 ) then
             MAG_TMP2 = MAG_OBS_TMP(ifilt2_obs)
             MAG_BESSELL_OBS(ifilt2_obs) = MAG_TMP2
             if ( MAG_TMP2 .GT. 40.0 ) LCRAZYMAG = .TRUE.
           endif
         ENDDO

         if ( .not. LCRAZYMAG ) then
           opt   = +1   ! flag for Bessell -> Landolt
           istat = Landolt_convert(opt
     &              ,MAG_BESSELL_OBS(IFILT_BESS_U)  ! input  UBVRI,BX
     &              ,MAG_OBS_TMP(IFILT_BESS_U)      ! output Landolt UBVRI
     &                  )
         endif

c abort if Landolt correction makes more than 3 mag change.
c Check only if SHAPE and COLOR have sane values,
c and also require reasonable Trest.
c
c
         DIF = MAG_BESSELL_OBS(ifilt_obs)-MAG_OBS_TMP(ifilt_obs)
         if (   abs(DIF)     .GT. 4.0   ! was 3.0
     &    .and. TREST        .LT. +50.0
     &    .and. TREST        .GT. -16.0
     &    .and. SHAPE(1)     .GT. PRIOR_SHAPE_RANGE(1)
     &    .and. SHAPE(1)     .LT. PRIOR_SHAPE_RANGE(2)
     &    .and. abs(AVHOST)  .LT. 10.0 ) then

           CALL PRINT_PREABORT_BANNER("USRFUN"//CHAR(0), 40)
           cfilt = filtdef_string(ifilt_obs:ifilt_obs)
           print*,' Filter = ', cfilt,' : '
           print*,' MAG(LANDOLT)-MAG(BESSELL) = ',
     &         MAG_OBS_TMP(ifilt_obs), ' - ',
     &         MAG_BESSELL_OBS(ifilt_obs), ' = ', DIF

           ABORT_ON_DMP = .TRUE.
           LDMP = .TRUE.

           c1err = 'Landolt-Bessell mag-dif is too large'
           c2err = 'Check Landolt transformation'
         endif

      ENDIF  ! end of USE_LANDOLT_OBS

c  strip off final observer-frame mag

      MAG_OBS      = MAG_OBS_TMP(ifilt_obs)

c ------------------------------------------
c Convert to calibrated flux if MAG_OBS has reasonable value;
c otherwise set flux to zero.

      ISOBS = (ZSN .GT. 1.0E-7)

      IF ( ISOBS ) THEN
         LTMP = (MAG_OBS .LT.  40.0) .and. (MAG_OBS .GT. 5.0)
      ELSE
         LTMP = (MAG_OBS .LT. -10.0) .and. (MAG_OBS .GT. -30.0)
      endif

c allow any MAG for TEST option
      if ( FITMODEL_INDEX .EQ. MODEL_FIXMAG ) LTMP = .TRUE.

      if ( LTMP ) then
         arg   = -0.4 * (MAG_OBS - ZEROPOINT_FLUXCAL_DEFAULT)
         FLUX  =  TEN8**(ARG)
      else
         FLUX = 0.0
      endif

c --------------------------------------------------------
502   CONTINUE  ! come here when observer-flux is calculated

      USRFUN = FLUX

      IF ( .not. USE_MODEL_MAGERR ) THEN
          MAG_ERR = 0.0   ! Apr 5 2016
      ENDIF
      IF ( FUDGE_MAGERR_MODEL .GE. 0.0 ) THEN
         MAG_ERR = FUDGE_MAGERR_MODEL
      ENDIF

c --------------------------------------------
c CHECK DUMP UTILITIES

      IF ( LDMP ) THEN  ! strip things for both obs- and rest-frame model

        ISN  = int( INIVAL(ipar_isn) )
        CID  = SNLC_CID
        MJD  = R8EP_MJD(IFITDATA_USRFUN)

        LPAR_SHAPE = index(PARNAME_STORE(IPAR_SHAPE), ' ' ) - 1
        LPAR_COLOR = index(PARNAME_STORE(IPAR_COLOR), ' ' ) - 1
        LPAR_X0    = index(PARNAME_STORE(IPAR_X0), ' ' ) - 1
      ENDIF

      IF ( LDMP .and. LREST_FITMODEL ) THEN

c write fit parameters

        print*,' - - -  - - - - - - - - - - - - - - - - - - - - -'
        write(6,701)
     &    PARNAME_STORE(IPAR_X0)(1:LPAR_X0), DIST,
     &    PARNAME_STORE(IPAR_COLOR)(1:LPAR_COLOR), AVHOST,
     &    PARNAME_STORE(IPAR_SHAPE)(1:LPAR_SHAPE), SHAPE(1),
     &    MJD, ZSN

701     format(T2,'USRFUN: ',A,'=',F7.3, 2x,A,'=',F7.4,2x,
     &              A,'=',F7.4, 2x, 'MJD=',F9.3, 2x,'Z=',F7.5 )

        cfilt = filtdef_string(ifilt_obs:ifilt_obs)
        ctmp2 = filtdef_string(ifilt_rest1:ifilt_rest1)
        write(6,702) cfilt, Tobs, ctmp2, Trest
702     format(T10, 'Tobs(',A1,')=',F8.3,2x,
     &        'Trest(',A1,')=',F8.3  )

        CALL FLUSH(6)


c write rest-frame info

c unextincted mag in rest frame
        MAG_TMP1 = MAG_REST(ifilt_rest1) - MAG_XTAV_REST(ifilt_rest1)

        write(6,703)
     &   filtdef_string(ifilt_rest1:ifilt_rest1), MAG_TMP1
     &  ,int(100.0*MAG_ERR+0.5)
     &  ,filtdef_string(ifilt_rest1:ifilt_rest1)
     &  ,MAG_REST(ifilt_rest1)

703     FORMAT(T10,'Mrest(',A,')=',F9.4,'(',I2.2,')',  2x,
     &            'XMrest(',A,')=',F9.4 )

c write rest color, AVwarp and Kcor

        write(6,704)
     &      filtdef_string(ifilt_rest1:ifilt_rest1)
     &     ,filtdef_string(ifilt_rest2:ifilt_rest2)
     &     ,MAG_REST(ifilt_rest1) - MAG_REST(ifilt_rest2)
     &     ,AVwarp
     &     ,filtdef_string(ifilt_rest1:ifilt_rest1)
     &     ,filtdef_string(ifilt_obs:ifilt_obs)
     &     ,MAG_KCOR(1), MAG_KCOR(2)

704      format(T10,'Xcol(',A,'-',A,')=', F7.4, 2x,'AVwarp=',F7.4,
     &           2x,'K_',A,A,'=',F7.4,'+-',F7.4 )

c write observer mag and flux

         write(6,706) filtdef_string(ifilt_obs:ifilt_obs),
     &                MAG_OBS, MAG_XTMW, FLUX
706      format(T10,'m_obs(',A,')=',F8.4, 2x, 'm(XTMW)=',F7.4,
     &              2x, 'Flux_obs=',G14.6 )

c now write single line with CID keyword ;
c grep "CID" > bla creates easy-to-read column-formatted file
c Columns are
c   1. CID
c   2. obsFilt
c   3. restColor
c   4. MJD
c   5. Trest
c   6. Unextincted mag in rest-frame
c   7. rest-frame mag
c   8. rest-frame color used for SED warping
c   9. AV warp
c  10. Kcor
c  11. observed mag

         CALL CIDSTRING(CID,CCID,LL)
         write(6,710) CCID(1:LL)
     &     ,filtdef_string(ifilt_obs:ifilt_obs)
     &     ,filtdef_string(ifilt_rest1:ifilt_rest1)
     &     ,filtdef_string(ifilt_rest2:ifilt_rest2)
     &     ,MJD, Trest
     &     ,MAG_TMP1, MAG_REST(ifilt_rest1)
     &     ,MAG_REST(ifilt_rest1) - MAG_REST(ifilt_rest2)
     &     ,AVwarp, MAG_KCOR(1), MAG_OBS

710      format(T2,A,  2x,A,1x,A,'-',A,1x,  F10.3, 7F9.4 )
         CALL FLUSH(6)

         IF ( ABORT_ON_DMP ) THEN
           CALL MADABORT("USRFUN", c1err, c2err )
         ENDIF

      ENDIF  ! end of dump for rest-frame model


c ===========================
c Now check dump for observer-frame model

      IF ( LDMP .and. LOBS_FITMODEL ) THEN

        print*,' - - -  - - - - - - - - - - - - - - - - - - - - -'

        write(6,751)
     &    PARNAME_STORE(IPAR_X0)(1:LPAR_X0), DIST,
     &    PARNAME_STORE(IPAR_COLOR)(1:LPAR_COLOR), AVHOST,
     &    PARNAME_STORE(IPAR_SHAPE)(1:LPAR_SHAPE), SHAPE(1),
     &    MJD

751     format(T2,'USRFUN: ',A,'=',G10.5, 2x, A,'=',F6.3, 2x,
     &              A,'=',F6.3, 2x, 'MJD=',F9.3 )

        write(6,752) Tobs, Trest, Zsn
752     format(T10, 'Tobs=',F7.2,2x, 'Trest=',F7.2, 2x,'Z=',F6.4 )

        cfilt = filtdef_string(ifilt_obs:ifilt_obs)
        write(6,754) cfilt, Flux, MAG_ERR
754     format(T5,'model Flux_OBS(',A1,') = ',
     &             G14.5, 3x,'MAG_ERR=', F8.5 )

        CALL FLUSH(6)

        IF ( USE_LANDOLT_OBS .and. LBESS_OBS ) then

           write(6,766) 'BESSELL',
     &        (MAG_BESSELL_OBS(ifilt_tmp),
     &          ifilt_tmp=IFILT_BESS_U, IFILT_BESS_BX)

           write(6,766) 'LANDOLT',
     &        (MAG_OBS_TMP(ifilt_tmp),
     &          ifilt_tmp=IFILT_BESS_U, IFILT_BESS_BX)

766        format(T5,'model MAG_',A,'(UBVRIX)=', 6F9.4 )

           print*, '      MAG_BESSELL(',cfilt,') = ',
     &     MAG_BESSELL_OBS(ifilt_obs),' -> ', MAG_OBS_TMP(ifilt_obs),
     &     ' (Landolt)'

        ELSE
            write(6,812) cfilt(1:1), MAG_OBS, Trest, ITER
812         format(T5,'model MAG_OBS(', A, ')=', F9.4,
     &           ' at Trest=',F7.2, 2x, 'ITER=',I1)
        ENDIF
        call FLUSH(6)

        IF ( ABORT_ON_DMP ) THEN
          CALL MADABORT("USRFUN", c1err, c2err )
        ENDIF

      END IF  ! end of dump for observer-frame model


      RETURN
      END   ! end of USRFUN

C ====================================================
CDECK  ID>,  GET_DIST8. 
      DOUBLE PRECISION FUNCTION GET_DIST8(Z, SHAPE, COLOR, SCALE)
c
c Created Aug 13, 2009 by R.Kessler
c
c Return "DISTANCE" estimate based on model;
c => MUREF - 2.5log10(SCALE) (distance modulus) for mlcs, stretch ...
c => X0*SCALE for SALT2
c
c Mar 24, 2012: add SCALE argument
c -------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





c +CDE,SNANAFIT.
c +CDE,FILTCOM.
c +CDE,SNLCINP.

c function inputs

      DOUBLE PRECISION
     &   Z, SHAPE, COLOR  ! (I) z, DELTA/x1,   c/AV
     &  ,SCALE            ! (I) include this multiplicative scale

c local var
      DOUBLE PRECISION  S2a, S2b, x0, MUREF

c function
      DOUBLE PRECISION  SALT2x0calc, DLMAG8_REF

C ---------- BEGIN -----------

      GET_DIST8 = 0.0
      MUREF     = DLMAG8_REF(Z)

      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
         S2a = DBLE(SALT2alpha)
         S2b = DBLE(SALT2beta)
         x0  = SCALE * SALT2x0calc( S2a, S2b, SHAPE, COLOR, MUREF)

         if ( OPT_SALT2FIT .EQ. 0 ) then
           GET_DIST8 = x0
         else if ( OPT_SALT2FIT .EQ. 1 ) then
           GET_DIST8 = log10(x0)
         else if ( OPT_SALT2FIT .EQ. 2 ) then
           GET_DIST8 = 0.0 ! MUDIF  estimate
         endif

      ELSE
         GET_DIST8 = MUREF - 2.5*LOG10(SCALE)
      ENDIF

      RETURN
      END  ! end of GET_DIST8

C ===================================================
CDECK  ID>,  GTSIMEFF. 
      DOUBLE PRECISION FUNCTION SNLC_FIT_SIMEFF(isn,XVAL)
c
c Created Jul 25, 2011
c Return simulated efficiency for this SN (ISN)
c and fit-parameters (XVAL)
c Fill variables needed to get efficiency,
c and then call utility GET_SIMEFFMAP().
c
c -----------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SIMEFFCM. inserted below by ypatchy. 

      INTEGER
     &   MXPAR_SIMEFF
     &  ,IPAR_SIMEFF_REDSHIFT
     &  ,IPAR_SIMEFF_MWEBV

      PARAMETER (
     &   MXPAR_SIMEFF         = 10
     &  ,IPAR_SIMEFF_REDSHIFT = 51  ! much larger than IPAR_MAX
     &  ,IPAR_SIMEFF_MWEBV    = 52
     &     )


      INTEGER
     &   NPAR_SIMEFF
     &  ,IPAR_SIMEFF(MXPAR_SIMEFF)

      REAL*8  PARVAL8_SIMEFF(MXPAR_SIMEFF) ! Z, AV, DELTA, etc ...
      COMMON / SIMEFFCM4 / NPAR_SIMEFF, IPAR_SIMEFF
      COMMON / SIMEFFCM8 / PARVAL8_SIMEFF


c function args
      INTEGER ISN          ! (I) sparse SN index
      REAL*8  XVAL(*)      ! (I) current fit parameters

c local variables

      REAL*8  EFF
      INTEGER OPTEFF, ipar, ipar2, j

c define EFFMIN so that EFF > 0 to avoid log(0) problems
      REAL*8 EFFMIN
      PARAMETER (EFFMIN = 1.0E-10)

c functions
      REAL*8   GET_SIMEFFMAP
      EXTERNAL GET_SIMEFFMAP  ! inside sntools.c

c  ------------- BEGIN ------------

      IF ( DOFIT_PHOTOZ ) THEN
        OPTEFF = 1     !   EFF -> EFF/EFFMAX
      ELSE
        OPTEFF = 0
      ENDIF

c load up the PARVAL_SIMEFF
      DO 100 ipar   = 1, NPAR_SIMEFF

         PARVAL8_SIMEFF(ipar) = -999.
         ipar2  = IPAR_SIMEFF(ipar)

         if ( ipar2 .LE. IPAR_MAX ) then
            PARVAL8_SIMEFF(ipar) = XVAL(IPAR2)
            goto 100
         endif

         if ( ipar2 .EQ. IPAR_SIMEFF_REDSHIFT ) then
            PARVAL8_SIMEFF(ipar) = ZSCALE_SIMEFF * XVAL(IPAR_zPHOT)
            goto 100
         endif

         if ( ipar2 .EQ. IPAR_SIMEFF_MWEBV ) then
            PARVAL8_SIMEFF(ipar) = SNLC_MWEBV
            goto 100
         endif

c if we get here then abort


100   CONTINUE


c get efficiency

      EFF = GET_SIMEFFMAP(OPTEFF, NPAR_SIMEFF, PARVAL8_SIMEFF )
      SNLC_FIT_SIMEFF = MAX(EFF,EFFMIN)


      RETURN
      END   ! end of SNLC_FIT_SIMEFF


C ====================================================
CDECK  ID>,  FITMODEL_INI. 
      SUBROUTINE FITMODEL_INI()
c
c Created Nov 2010 by R.Kessler
c Use namelist input FITMODEL_NAME to initialize global
c variables
c   FITMODEL_PATH, FITMODEL_VERSION, FITMODEL_INDEX
c
c Feb 22 2017:
c   + allow FITMODEL_NAME to include path; see EXTRACT_MODELNAME().
c
c May 31 2019: check for SALT3 model.
c
c -----------------------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





c local var

      INTEGER
     &    j, LM, L0, L1, L2, L3
     &   ,LEN_MODELNAME, LEN_ROOT, LEN_PATH, LEN_VERS

      character
     &   STRUP*(MXCHAR_MODELNAME)
     &  ,STRLO*(MXCHAR_MODELNAME)
     &  ,tmpFile*(MXCHAR_FILENAME)
     &  ,mtmp*(MXCHAR_MODELNAME)
     &  ,strdefault*20
     &  ,USER_FITMODEL_NAME*(MXCHAR_FILENAME)
     &  ,C_FITMODEL*(MXCHAR_FILENAME)
     &  ,C_PATH*(MXCHAR_FILENAME), C_VERSION*(MXCHAR_MODELNAME)

      LOGICAL USE_DEFAULT

c functions
      CHARACTER*80 RDSTRING

c ------------ BEGIN --------------

      LM = INDEX(FITMODEL_NAME,' ') - 1
      IF ( LM .GE. MXCHAR_FILENAME .or. LM < 1 ) THEN
         write(c1err,61) MXCHAR_FILENAME
 61      format('len(FITMODEL_NAME) exceeds MXCHAR_FILENAME=',I3)
         c2err = 'Please try a shorter FITMODEL_NAME.'
         CALL MADABORT("FITMODEL_INI", c1err, c2err)
      ENDIF

      FITMODEL_INDEX   = -9
      FITMODEL_PATH    = ''
      FITMODEL_VERSION = ''

      DO 10  j = 1, MXMODEL_INDEX
        FITMODEL_LIST(j) = ''
10    CONTINUE

c first  hard-wird generic name for each model
      FITMODEL_LIST(MODEL_STRETCH)  = 'stretch'
      FITMODEL_LIST(MODEL_STRETCH2) = 'stretch2'
      FITMODEL_LIST(MODEL_mlcs2k2)  = 'mlcs2k2'
      FITMODEL_LIST(MODEL_SALT2)    = 'SALT2'
      FITMODEL_LIST(MODEL_SALT3)    = 'SALT3'
      FITMODEL_LIST(MODEL_BAYESN)   = 'BAYESN'
      FITMODEL_LIST(MODEL_snoopy)   = 'snoopy'
      FITMODEL_LIST(MODEL_SIMSED)   = 'SIMSED'

      USER_FITMODEL_NAME = FITMODEL_NAME ! transfer to local variable

c Special case for backward compatibility: for mlcs, change to mlcs2k2 ...
c remove this dumb logic if/when a new MLCS model is provided by the ESSENCE group.
      if ( FITMODEL_NAME .EQ. 'mlcs' .or.
     &     FITMODEL_NAME .EQ. 'MLCS' ) then
        USER_FITMODEL_NAME = FITMODEL_LIST(MODEL_mlcs2k2)
      endif

c Feb 22 2017:
c  check if FITMODEL_NAME includes path.
c  Note that C function return termination string
      L0 = INDEX(USER_FITMODEL_NAME,' ') - 1
      C_FITMODEL = USER_FITMODEL_NAME(1:L0) // char(0)

      CALL EXTRACT_MODELNAME(C_FITMODEL,    ! input
     &      C_PATH, C_VERSION,              ! output
     &      MXCHAR_FILENAME, MXCHAR_FILENAME, MXCHAR_MODELNAME)

      LEN_PATH = INDEX(C_PATH,    char(0) ) - 1
      LEN_VERS = INDEX(C_VERSION, char(0) ) - 1
      FITMODEL_PATH    = C_PATH(1:LEN_PATH)
      FITMODEL_VERSION = C_VERSION(1:LEN_VERS)

c now get FITMODEL_INDEX ....

      DO 20  j = 1, MXMODEL_INDEX
         if ( FITMODEL_LIST(j) .EQ. ' ' ) GOTO 20

c check both upper & lower case
         CALL UPCASE(FITMODEL_LIST(j),STRUP)
         CALL LOCASE(FITMODEL_LIST(j),STRLO)
         LM = INDEX(FITMODEL_LIST(j),' ') - 1

         IF ( STRUP(1:LM) .EQ. FITMODEL_VERSION(1:LM)  .or.
     &        STRLO(1:LM) .EQ. FITMODEL_VERSION(1:LM) ) THEN
            FITMODEL_INDEX = j
            LEN_MODELNAME  = LM
         ENDIF
20    CONTINUE

c May 31 2019 hack: if SALT3, switch to SALT2 to avoid lots of code refactor.
      if ( FITMODEL_INDEX == MODEL_SALT3 ) FITMODEL_INDEX=MODEL_SALT2

c abort if FITMODEL_INDEX has not been found.

      IF ( FITMODEL_INDEX .LE. 0 ) THEN
        LM = INDEX(FITMODEL_NAME,' ') - 1
        c1err = 'Unknown FITMODEL_NAME = ' //  FITMODEL_NAME(1:LM)
        c2err = 'Check &FITINP namelist parameter'
        CALL MADABORT("FITMODEL_INI", c1err, c2err)
      ENDIF



c ----------------------------
c finally, if FITMODEL_PATH is not already set above
c with EXTRACT_MODELNAME, then set it here to default path.

      LEN_PATH = INDEX(FITMODEL_PATH, ' ') -1
      IF ( LEN_PATH == 0 ) THEN
         LEN_VERS = INDEX(FITMODEL_VERSION,' ') - 1
         FITMODEL_VERSION = FITMODEL_VERSION(1:LEN_VERS)

         LEN_ROOT = INDEX(SNDATA_ROOT,' ') - 1
         FITMODEL_PATH = SNDATA_ROOT(1:LEN_ROOT) //
     &       '/models/' // MTMP(1:L0)  //  '/' //
     &       FITMODEL_VERSION(1:LEN_VERS)
      ENDIF

      RETURN
      END   ! end FITMODEL_INI

C ========================
CDECK  ID>,  GET_FITFLUX. 
      SUBROUTINE GET_FITFLUX(ep, FIT_FLUXCAL, FIT_FLUXCAL_ERR, REJECT)

c Created Mar 17 2021
c Interface for snana to fetch fitted FLUXCAL and error;
c e.g., for OUTLIER table.

      IMPLICIT NONE
      INTEGER EP                         ! (I) epoch index
      REAL FIT_FLUXCAL, FIT_FLUXCAL_ERR  ! (O) fitted flux and erro
      LOGICAL  REJECT                    ! (O) T -> epoch rejected


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.    public snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.    local fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )




C  -------------- BEGIN ------------
      FIT_FLUXCAL       = R4EP_ALL(ep,JEP_MODELFLUX)
      FIT_FLUXCAL_ERR   = R4EP_ALL(ep,JEP_MODELFLUX_ERR)

      REJECT =
     &  ( I4EP_ALL(ep,IEP_REJECT)  > 0 ) .or.
     &  ( I4EP_ALL(ep,IEP_REJECT2) > 0 )

      RETURN
      END     ! end GET_FITFLUX

C ========================================================
CDECK  ID>,  GET_FLUX_FITFUN. 
      DOUBLE PRECISION FUNCTION GET_FLUX_FITFUN
     &                    ( ifilt_obs, T8obs, opt )
c
c Wrapper to call USRFUN with final "FITVAL" arguments.
c Call this after fit to get function value; do NOT use
c this before or during fit !!!
c
c OPT = 0  : return nominal function: observer-frame flux
c OPT = 1  : return rest-frame flux
c                (i.e.; no K-cor, no dL, include AV)
c
c OPT = 2  : return rest-frame flux based on cosmology and XMW
c              (for training)
c OPT = 3  : same as OPT=2, but subtract host-extinction too
c
c OPT = 6  : return rest-frame mag-error instead of flux
c OPT = 10 : return K-correction only
c OPT = 60 : return error on observer-frame flux
c OPT = 99 : return simulated observer flux with no smearing (LSIM=T only)
c
c
c     HISTORY
c  ~~~~~~~~~~~~
c Jan 25, 2007: add AVMW arg to USRFUN
c
c Apr 26, 2007: use LCVAL_STORE instead of FITVAL in order
c               to use marginalized values.
c
c Mar 24, 2008: add OPT=2 to return rest-flux based on cosmology
c               and ignoring MLCS model.
c
c Feb 13, 2012: For REST option
c     - set MWEBV=0
c     - set DISTPAR8 = GET_DIST8(Zat10pc ...)
c
c May 21, 2012: remove ISN arg.
c --------------------------------------

      IMPLICIT NONE

c define function input
      INTEGER IFILT_OBS    ! (I) SN and obs filter index
      REAL*8  T8obs             ! (I) MJD - MJDatPk1
      INTEGER opt               ! (I) option


c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.    public snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.    local fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP.     NFIT_ITERATION is here inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      REAL*8
     &   Flux8, Z8, DISTPAR8, COLORPAR8
     &  ,RVHOST8, DLMAG8, SHAPEPAR8(2)
     &  ,AVwarp8, KCOR8(2), MAGERR8, MWEBV8
     &  ,ERRFRAC8, XTAV, XTMW
     &  ,FITPARLOC8(IPAR_MAX)
     &  ,SIMPARLOC8(IPAR_MAX)
     &  ,MAGTMP8, ARG8
     &  ,X08, S2a, S2b

      INTEGER ipar
      LOGICAL LDMP, LFLUX, LREST_COSMO, LMUFIX


c function
      REAL*8  USRFUN, DLMAG8_REF, GET_RV8, GET_DIST8

C -------------- BEGIN ----------------

      GET_FLUX_FITFUN = -9.0

      DO ipar = 1, IPAR_MAX
        FITPARLOC8(ipar) = LCVAL_STORE(ipar)
        SIMPARLOC8(ipar) = SIMVAL_STORE(ipar)
      ENDDO
      MWEBV8 = DBLE ( SNLC_MWEBV )

      LREST_COSMO = OPT.EQ.2 .or. OPT.EQ. 3

      IF ( OPT.EQ.1 .or.  OPT.EQ.6 ) then  ! fit-model flux, rest-frame
          Z8           = Zat10pc
          COLORPAR8    = FITPARLOC8(IPAR_AV)
          RVHOST8      = GET_RV8(FITPARLOC8)
          SHAPEPAR8(1) = FITPARLOC8(IPAR_SHAPE)
          SHAPEPAR8(2) = FITPARLOC8(IPAR_SHAPE2)
          DISTPAR8     = GET_DIST8(Zat10pc,SHAPEPAR8(1),COLORPAR8,ONE8)
          MWEBV8       = 0.0

      ELSE IF ( OPT .EQ.  0 .or.
     &          OPT .EQ. 60 .or.
     &          OPT .EQ. 10 .or.
     &          LREST_COSMO
     &            ) THEN

c  fit-model flux, observer
          Z8           = FITPARLOC8(IPAR_zPHOT)
          DISTPAR8     = FITPARLOC8(IPAR_DLMAG)
          COLORPAR8    = FITPARLOC8(IPAR_AV)
          RVHOST8      = GET_RV8(FITPARLOC8)
          SHAPEPAR8(1) = FITPARLOC8(IPAR_SHAPE)
          SHAPEPAR8(2) = FITPARLOC8(IPAR_SHAPE2)

          LMUFIX = DOFIT_PHOTOZ .and. (INISTP_DLMAG .EQ. 0.0)
          if ( LMUFIX ) THEN
             DLMAG8   = DLMAG8_REF(Z8)
             DISTPAR8 = GET_DIST8(Z8,SHAPEPAR8(1),COLORPAR8,ONE8)
          endif  ! LMMUFIX

      ELSE IF ( OPT .EQ. 99 ) THEN
          Z8           = SIMPARLOC8(IPAR_zPHOT)
          COLORPAR8    = SIMPARLOC8(IPAR_AV)
          RVHOST8      = GET_RV8(SIMPARLOC8)
          DISTPAR8     = SIMPARLOC8(IPAR_DLMAG)
          SHAPEPAR8(1) = SIMPARLOC8(IPAR_SHAPE)
          SHAPEPAR8(2) = SIMPARLOC8(IPAR_SHAPE2)
      ELSE
         write(c1err,660) OPT
660      format('Invalid OPT=',I4 )
         CALL MADABORT("GET_FLUX_FITFUN", c1err, "")
      ENDIF


      LDMP = LDMPFUN(IFILT_OBS)

      FLUX8 =
     &       USRFUN ( NFIT_ITERATION
     &                ,ifilt_obs          ! (I) obs-frame filter
     &                ,Z8, T8obs          ! (I) redshift and epoch
     &                ,SHAPEPAR8          ! (I) Delta, stretch, x1 ...
     &                ,DISTPAR8           ! (I) MU or x0
     &                ,COLORPAR8          ! (I) AV or c
     &                ,RVHOST8            ! (I) RV
     &                ,MWEBV8             ! (I) MW extinction
     &                ,LDMP               ! (I) dump flag
     &                ,AVwarp8, KCOR8     ! (O)
     &                ,XTAV, XTMW         ! (O)
     &                ,MAGERR8            ! (O) return args
     &              )

      IF ( OPT .EQ. 6 ) then
        GET_FLUX_FITFUN = MAGERR8

      ELSE IF ( LREST_COSMO ) THEN

        magtmp8 = -2.5*DLOG10(FLUX8) + ZEROPOINT_FLUXCAL_DEFAULT
     &            -(XTMW + KCOR8(1) + DLMAG8_REF(Z8) )

        if ( OPT .EQ. 3 ) magtmp8 = magtmp8 - XTAV

        ARG8 = -0.4 * ( MAGTMP8 - ZEROPOINT_FLUXCAL_DEFAULT)
        GET_FLUX_FITFUN = TEN8**ARG8

cc  xxxxxxx
cc        GET_FLUX_FITFUN = ADUSCALE * TEN8**(-0.4*MAGTMP8)
cc xxxxxxxxx

c -------------
c        print*,' XXXXX ------------------------------------- '
c        print*,' XXXXX ifilt_obs, Tobs = ', ifilt_obs, T8obs
c        print*,' XXXXX XTMW, KCOR = ', XTMW, KCOR8(1)
c        print*,' XXXXX Z, MU = ', Z8, DLMAG8_REF(Z8)
c        print*,' XXXXX FLUX8, MAGTMP8 = ', FLUX8, MAGTMP8
c -------------

      ELSE IF ( OPT .EQ. 60 ) then
        errfrac8        = 1.0 - TEN8**(-0.4*MAGERR8)
        GET_FLUX_FITFUN = FLUX8 * errfrac8
      ELSE IF ( OPT .EQ. 10 ) then
        GET_FLUX_FITFUN = KCOR8(1)
      ELSE
        GET_FLUX_FITFUN = FLUX8
      ENDIF

      RETURN
      END     ! end of GET_FLUX_FITFUN


C ================================================
CDECK  ID>,  GET_RV8. 
      DOUBLE PRECISION FUNCTION GET_RV8(FITPAR8)
c
c Sep 29, 2007
c Returns RV for fitter-function USRFUN
c
c Aug 1, 2009: RV8=1000 (instead of RV_MWDUST) if AV/RV=0
c
c ----------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.   private fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      REAL*8  FITPAR8(IPAR_MAX)  ! (I) fit-params

c local var

      LOGICAL LDMP
      REAL*8  RV8, AV8, AV8RV8

c ------------ BEGIN ---------

      LDMP = .FALSE.

      GET_RV8 = RV_MWCOLORLAW

      IF ( INISTP_AVRV .NE. 0.0 ) THEN
         AV8RV8 = FITPAR8(IPAR_AVRV)   ! AV/RV ratio
         AV8    = FITPAR8(IPAR_AV)
         if ( abs(AV8RV8) .GT. 1.0E-5 ) then
           RV8    = AV8 / AV8RV8
         else
           RV8    = 10.
         endif
      ELSE
         RV8  = FITPAR8(IPAR_RV)
      ENDIF

      GET_RV8 = RV8

      RETURN
      END

C ==============================
CDECK  ID>,  RSTFLTWGT. 
      SUBROUTINE RESTFILT_WGT (
     &    LAMREST            ! (I) rest-frame wavelegth
     &   ,ifilt_rest1        ! (I) index of nearest rest-filter
     &   ,ifilt_rest2        ! (I) index of 2nd nearest filter
     &   ,WGT1, WGT2         ! (O) return wgts (sum to 1)
     &      )

c Created Aug 26,2009 by R.Kessler
c
c Return rest-filter weights to allow a smooth transition
c across filters. At a transition wavelength (i.e., 3900 A
c between U & B), WGT1 = WGT2 = 0.5. If more than
c "LAMREST_MODEL_SMOOTH" Anstroms away from transition
c wavelength, return WGT=1 and WGT=0
c
c These weights can then be used to smooth out the
c model mags and/or errors
c
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.   private fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c subroutine args

      REAL*8  LAMREST, WGT1, WGT2
      INTEGER ifilt_rest1, ifilt_rest2

c local var

      REAL*8
     &   LAMAVG(2)
     &  ,LAMBOUNDARY
     &  ,LAMDIST
     &  ,LAMDIST_MAX

c function
      REAL*8 SMOOTH_STEPFUN8

C -------------- BEGIN ------------

      WGT1 = 1.0 ! default output
      WGT2 = 0.0

      IF ( LAMREST_MODEL_SMOOTH .LE. 0.0 ) RETURN
      IF ( IFILT_REST1 .EQ. IFILT_REST2  ) RETURN

      LAMAVG(1) = FILTREST_LAMAVG(ifilt_rest1)
      LAMAVG(2) = FILTREST_LAMAVG(ifilt_rest2)

      IF ( LAMAVG(1) .GT. LAMAVG(2) ) THEN
        LAMBOUNDARY = FILTREST_LAMRANGE(1,ifilt_rest1)
      ELSE
        LAMBOUNDARY = FILTREST_LAMRANGE(2,ifilt_rest1)
      ENDIF

c get distance (Ansgrroms) from boundary
      LAMDIST = abs(LAMREST - LAMBOUNDARY)

c bail if too far from boundary
      IF ( LAMDIST .GT. LAMREST_MODEL_SMOOTH ) RETURN

c use SMMOOTH_STEPFUN function normalized to be
c zero  at LAMBOUNDARY - LAMREST_MODEL_SMOTH, and
c one   at LAMBOUNDARY + LAMREST_MODEL_SMOTH

      LAMDIST_MAX = DBLE ( LAMREST_MODEL_SMOOTH )
      WGT1   = SMOOTH_STEPFUN8(LAMDIST, LAMDIST_MAX )
      WGT2   = 1.0 - WGT1

      RETURN
      END


C ===========================================
CDECK  ID>,  DATA_MODEL_RATIO. 
      REAL FUNCTION DATA_MODEL_RATIO(ifilt)

c
c Return wgt average of data/model for point on lightcurve.
c This is used for adjusting initial "fluxnorms" for fit.
c Uses EP_XXX arrays, and assumes that they have been
c filled with a call to FCNSNLC with IFLAG=FCNFLAG_USER
c
c Aug 15, 2012: remove obsolet ISN arg.
c Jan 25, 2014: use new I4/R4EP_ALL arrays
c ---------------------

      IMPLICIT NONE

      INTEGER  ifilt   ! (I) sparse filter index

c local


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER imjd, ifilt_obs, i, ep

      REAL RAT, ERR, RSUM, WSUM, w, TREST
      INTEGER NEPFIT

c functions
      LOGICAL MJDSELECT

c ------------- BEGIN ---------

      DATA_MODEL_RATIO = 1.0E-9

      ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
      if ( .NOT. USE_FILT(ifilt_obs) ) return

      RSUM = 0.0
      WSUM = 0.0
      NEPFIT = 0

      DO 100 i = 1, NFITDATA + NFITDATA_REJECT

         ep   =   EPLIST_FIT(i)

c pick out epochs from only the input IFILT
         IF ( IFILT .NE. I4EP_ALL(ep,IEP_IFILT) ) goto 100

         IMJD =   I4EP_ALL(ep,IEP_IMJD)
         if ( .not. MJDSELECT(imjd,0) ) goto 100

c exclude early or late times to be safe
         TREST = R4EP_ALL(ep,JEP_TREST)
         if ( TREST .LT. -10. ) goto 100
         if ( TREST .GT.  40. ) goto 100

         RAT  = R4EP_ALL(ep,JEP_RATIO) ! data/fit ratio
         ERR  = R4EP_ALL(ep,JEP_RATIO_ERR)

         if ( RAT > 0.0 .and. ERR > 0.0 ) then
            w      = 1.0/ERR**2
            RSUM   = RSUM + W * RAT
            WSUM   = WSUM + W
            NEPFIT = NEPFIT + 1
         endif

 100  CONTINUE

      if ( WSUM .NE. 0.0 ) then
         DATA_MODEL_RATIO = RSUM / WSUM
      else
         DATA_MODEL_RATIO = 1.0
      endif

      RETURN
      END

C ===========================================
CDECK  ID>,  RDFITNML. 
      SUBROUTINE RDFITNML(IERR)
c
c
c Read &FITINP namelist.
c
c HISTORY
c ---------------------
c
c Sep 30, 2090: Hard-wire DOCHI2_SIGMA = .TRUE.  for photoz fits
c
c Jul 20, 2011: on error call MADABORT with informative message
c               rather than returning IERR=-1.
c
c Jul 25, 2011: abort if OPT_SIMEFF != 0
c
c Aug 20, 2011:
c  FITWIN_CHI2SIGMA is wide open by default instead of -10 to 50
c
c Aug 28, 2012: udpate defaults for OPT_XTMW_ERR and OPT_COVAR_FLUX
c Mar 17, 2018: INISTP_COLOR -> 0.03 (was 0.2)
c -------------------------------------
      IMPLICIT NONE


C +CDE,SNFITPAR.   NULLVAL is here inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )



      INTEGER IERR ! (O) 0 => OK

c local var

      INTEGER IFILT, i
      REAL CUTINI(2), TMPCUT
      LOGICAL USE_AVPRIOR

      CHARACTER ctmp*4

C ------------------- BEGIN ---------------------

      CALL PRBANNER ( " READ &FITINP NAMELIST" )
      IERR = 0

      CUTINI(1) = -9.0E8
      CUTINI(2) = +9.0E8

      LTRACE = .FALSE.
      LPLOTCHI2 = .FALSE.
      IPAR_PLOTCHI2 = 0
      NFIT_VERBOSE  = 20

c init namelist defaults

      FITMODEL_NAME       = ' '

      RESTLAMBDA_FITRANGE(1) =     0.0
      RESTLAMBDA_FITRANGE(2) = 25000.0
      UVLAM_EXTRAPFLUX       = -9.0

c set defgaults to no rejected epochs at 2nd iteration
      DELCHI2_REJECT   = 1.0E9
      FITWIN_TREST(1)  = -999.0
      FITWIN_TREST(2)  = +999.0

      FITWIN_TREST_FILTER = ' '

      FITWIN_MJD(1)    = 20000.0
      FITWIN_MJD(2)    = 80000.0

      PEAKMJD_SANITY(1) = 0.0   ! 0 => -20/+5 days from start/end of season
      PEAKMJD_SANITY(2) = 1.0E6

      SIGNOISE_REJECT  = -9.0

      DO i = 1, 20
        CONTOUR_LIST(1,i) = 0
        CONTOUR_LIST(2,i) = 0
        CONTOUR_LIST(3,i) = 0
        CONTOUR_LIST(4,i) = 0
      ENDDO

      DO i = 1, 2
        FITWIN_ZPULL(i)      = CUTINI(i)
        FITWIN_ZPHOT(i)      = CUTINI(i)
        FITWIN_COLOR(i)      = CUTINI(i)
        FITWIN_SHAPE(i)      = CUTINI(i)
        FITWIN_PROB(i)       = CUTINI(i)
        FITWIN_NOMARG_PROB(i)  = CUTINI(i)
        FITWIN_CHI2SIGMA(i)    = CUTINI(i)
        FITWIN_TREST(i)        = CUTINI(i)
        FITWIN_MJD(i)          = CUTINI(i)

        FITWIN_COV_OFFDIAG(i)  = CUTINI(i)

        if ( i .eq. 1 ) TMPCUT = 0.0
        if ( i .eq. 2 ) TMPCUT = sqrt(CUTINI(i)) ! so that COVCUT is ok
        FITWIN_PEAKMJD_ERR(i)  = TMPCUT  ! cut in sigma(fitPar)
        FITWIN_MB_ERR(i)       = TMPCUT
        FITWIN_SHAPE_ERR(i)    = TMPCUT
        FITWIN_COLOR_ERR(i)    = TMPCUT

        FITWIN_PEAKMJD_ERRz1(i)  = TMPCUT ! cut on sigma(fitPar)/(1+z)
        FITWIN_MB_ERRz1(i)       = TMPCUT
        FITWIN_SHAPE_ERRz1(i)    = TMPCUT
        FITWIN_COLOR_ERRz1(i)    = TMPCUT
      ENDDO

c hard-wire a few very loose cuts on SALT2-fitted errors
c to reject crazy fits
      FITWIN_COV_OFFDIAG(1)   = -8.0
      FITWIN_COV_OFFDIAG(2)   = +8.0
      FITWIN_MB_ERR(2)        = +1.0

      SNMAGRMS_for_PHOTOZ = 0.12

      INISTP_PEAKMJD   = 2.0
      INISTP_AV        = 0.2
      INISTP_COLOR     = 0.03   ! Mar 17 2018 (was 0.2)
      INISTP_RV        = 0.0
      INISTP_AVRV      = 0.0
      INISTP_SHAPE     = 0.3
      INISTP_SHAPE2    = 0.0
      INISTP_DLMAG     = 0.5
      INISTP_X0        = 1.0E-5
      INISTP_PHOTOZ    = 0.0

      INIVAL_PEAKMJD       = NULLVAL
      INIVAL_PEAKMJD_SHIFT = 999999.
      INIVAL_AV        = NULLVAL
      INIVAL_RV        = RV_MWCOLORLAW
      INIVAL_AVRV      = 0.1
      INIVAL_COLOR     = 0.01
      INIVAL_DLMAG     = NULLVAL
      INIVAL_X0        = NULLVAL
      INIVAL_SHAPE     = NULLVAL
      INIVAL_SHAPE2    = NULLVAL
      INIVAL_PHOTOZ    = NULLVAL
      INIVAL_SHIFT_ERRFRAC = 0.0
      FRACERRDIF_REPEATFIT = 1.0E9

c setup default grid w.r.t. peakmjd-estimate
      INIVAL_GRIDSEARCH_DPEAKMJD(1) = -4.0  ! min MJD - PEAKMJD_APPROX (days)
      INIVAL_GRIDSEARCH_DPEAKMJD(2) = +4.0  ! max
      INIVAL_GRIDSEARCH_DPEAKMJD(3) = +2.0  ! bin size , days
      INIVAL_GRIDSEARCH_COLOR(1)   = 0.0
      INIVAL_GRIDSEARCH_COLOR(2)   = 0.0
      INIVAL_GRIDSEARCH_COLOR(3)   = 0.0


      USESIM_AV       = .FALSE.
      USESIM_COLOR    = .FALSE.
      USESIM_RV       = .FALSE.
      USESIM_SHAPE    = .FALSE.
      USESIM_LUMIPAR  = .FALSE.  ! legacy variable
      USESIM_PEAKMJD  = .FALSE.
      USESIM_DLMAG    = .FALSE.
      USESIM_REDSHIFT = .FALSE.
      USESIM_INIVAL   = .FALSE.

      LKCOR_AVWARP  = .TRUE.
      LKCOR_STRETCH = .FALSE.
      LFIXPAR_ALL   = .FALSE.
      LFIXPAR_ADJUST = .FALSE.

      DOCHI2_SIGMA = .FALSE.  ! May 8, 2009
      CHECK_CRAZYFITERR  = .TRUE.

      LDMP_PHOTOZ_DROPFILTER = .FALSE.
      DOFIT_PHOTOZ       = .FALSE.
      SKIP_PHOTOZ_INIT = .FALSE.
      LAMREST_MODEL_SMOOTH = -9.0

      OPT_PHOTOZ       = 0
      PHOTODZ_REJECT   = 0.05    ! initial W.A.G; users should test this
      PHOTODZ1Z_REJECT = -99.0   ! no cut
      PHOTOZ_BOUND(1)  = 1.0E-6
      PHOTOZ_BOUND(2)  = 1.4
      PHOTOZ_ITER1_LAMRANGE(1) =  4000.  ! default => skip UV region;
      PHOTOZ_ITER1_LAMRANGE(2) = 26000.  ! note this is obs-frame !

      ISCALE_COURSEBIN_PHOTOZ = 1
      NEVAL_MCMC_PHOTOZ      =  0
      PARLIST_MCMC_PHOTOZ(1) =  float(NEVAL_MCMC_PHOTOZ)
      PARLIST_MCMC_PHOTOZ(2) =  20.0  ! NEVAL before reducing step size
      PARLIST_MCMC_PHOTOZ(3) =  0.33  ! initial STEP = range * par(3)
      PARLIST_MCMC_PHOTOZ(4) =  0.90  ! step reduction factor
      PARLIST_MCMC_PHOTOZ(5) =  1.00  ! dmu range on mu constraint

      MINOS_ERRMAX_BAD  = .TRUE.
      MINOS_ERR_DLMAG   = .FALSE.
      MINOS_ERR_REQALL0 = .FALSE.
      MINOS_ERR_REQALL1 = .FALSE.
      OPT_COVAR_LCFIT = 0   ! default: do not fix un-invertible COV(x0,x1,c)

      SIMEFF_FILE   =  ' '

      STRETCH_TEMPLATE_FILE = ' '
      SALT2_DICTFILE        = ' '
      SALT2alpha            = 0.14  ! -> JLA value, Dec 2014
      SALT2beta             = 3.20  ! -> JLA value
      OPT_SALT2FIT          = 0  ! 0 => nominal SALT2 defn

      ZSCALE_SIMEFF = 1.0

      TREST_PEAKRENORM(1) = 0.0  ! default is no peak renorm
      TREST_PEAKRENORM(2) = 0.0

c Set option for covariance matrix.
c -9 => use default for each model (Aug 28, 2012)
c  0 => use diagonal elements only
c  1 => use covariance matrix evaluated between iterations
c  2 => use covaraince matrix evaluated each fit trial (slower)
      OPT_COVAR      = -99 ! legacy variable
      OPT_COVAR_FLUX = -9  ! new variable name, Nov 9 2018

c option for covariance errors on Galactic-extinction
      OPT_XTMW_ERR      = -9 ! Sep 22: legacy variable off
      OPT_COVAR_MWXTERR =  1 ! Aug 28, 2012: default is ON

c extinction options (also see GET_SNXT8 in snana.car):
c  1 => use default extinction from CCM89 law
c  2 => use Saurabh's parametrized extinction from alphs,beta,zeta

      OPT_SNXT     = OPT_SNXT_CCM89

c set algorithm for picking rest-frame color
c   1 => use two closest rest-frame filters
c   5 => use closest filter, and then use color corresponding
c        to Saurabh's lookup (use this option for sync-tests only)

      OPT_NEARFILT   = OPT_FILTOBS  ! obsolete : Feb 3 2012

c set option for Kcor errors; use SJ option (=2) as default
      OPT_KCORERR = OPT_KCORERR_SJ

c scale covariance matrix.
      SCALE_COVAR    = 1.0  ! default scale is 1 => nominal matrix

      FUDGE_COVAR    = 0.0  ! default is no fudge

      USE_MODEL_MAGERR = .TRUE.

      ADD_SALT2ERR_FROMz     = .FALSE.
      ENABLE_MAGSHIFT_SALT2  = .TRUE.
      ENABLE_WAVESHIFT_SALT2 = .TRUE.
      ALLOW_NEGFLUX_SALT2    = .TRUE.  ! default: allow UV Flam<0

c set default Landolt option OFF
      OPT_LANDOLT = 0
      do i = 1, 10
        LANDOLT_COLOR_SHIFT(i) = 0.0
      enddo

      UCOR_BXB    = .FALSE.

c ---------------------------------
      NGRID_PDF      = 0
      NSIGMA_PDF     = 4
      MAX_INTEGPDF   = 3

      PRIOR_AVEXP(1)   = 0.334   ! prior = exp(-AV/PRIOR_AVEXP)
      PRIOR_AVEXP(2)   = 1.0E9   ! prior = exp(-AV/PRIOR_AVEXP)
      PRIOR_AVWGT(1)   = 1.0     ! relative wgt of 1st expon
      PRIOR_AVWGT(2)   = 0.0     ! relative wgt of 2nd expon

      PRIOR_AVRES      = 0.0     ! smear AV prior by this resolution
      PRIOR_MJDSIG     = 20.0    ! sigma for gauss prior on PEAKMJD (days)
      PRIOR_ZERRSCALE  = 1000.0   ! default is no prior
      PRIOR_MUERRSCALE = 1000.0   ! default is no prior
      DOPRIOR_DLMAG    = .FALSE.

      OPT_PRIOR      = 1
      OPT_PRIOR_AV   = 1
      OPT_PRIOR_SIMEFF = 0
      OPT_SIMEFF     = 0   ! obsolete ; abort if set to non-zero

      OPT_MNSTAT_COV = 1   ! 1-> repeat fit on MNSTAT_COV<3 (bad cov)

      SIMFIT_IDEAL_PRESCALE = 0  ! zero --> OFF

c init to wide open
      PRIOR_LUMIPAR_RANGE(1) = -9.0  ! legacy variable
      PRIOR_LUMIPAR_RANGE(2) = +9.0  ! idem
      PRIOR_LUMIPAR_SIGMA    =  0.1  ! idem

      PRIOR_SHAPE_RANGE(1) = -9.0  ! LUMIPAR -> SHAPE (Apr 2013)
      PRIOR_SHAPE_RANGE(2) = +9.0
      PRIOR_SHAPE_SIGMA    =  0.1  ! Gauss roll-off at edges of flat prior


      PRIOR_SHAPE2_RANGE(1) = -9.0  !
      PRIOR_SHAPE2_RANGE(2) = +9.0
      PRIOR_SHAPE2_SIGMA    =  0.1  ! Gauss roll-off at edges of flat prior



      PRIOR_COLOR_RANGE(1) = -9.0
      PRIOR_COLOR_RANGE(2) = +9.0
      PRIOR_COLOR_SIGMA    =  0.01  ! Gauss roll-off at edges of flat prior

c Aug 17 2015: from snlc_sim.defaults since this is no longer read
      PRIOR_DELTA_PROFILE(1) =  0.23  ! sigma(low)
      PRIOR_DELTA_PROFILE(2) =  0.48  ! sigma(upper)
      PRIOR_DELTA_PROFILE(3) = -0.24 ! bifurcate Gaussian peak
      PRIOR_DELTA_PROFILE(4) =  0.1  ! minimum prob (allows tails)

      DOFIT_FILT(0) = .FALSE.  ! protect against passing ifilt_obs=0

      FILTER_FITMAGDIF = ''

      FILTLIST_FITRESTMAG  = ''
      COLORFIX_FITRESTMAG  = 999.  ! crazy value -> use best-fit value
      LUMIFIX_FITRESTMAG   = 999.  ! crazy value -> use best-fit value
      SHAPEFIX_FITRESTMAG  = 999.
      LAMEXTRAP_FITRESTMAG = 0.0
      DLAMTOL_FITRESTMAG   = 0.0  ! Mar 28 2020

      FILTLIST_FIT    = ''
      FILTLIST_DMPFCN = ''
      FILTLIST_DMPFUN = ''
      FILTLAM_SHIFT   = ''
      TREST_DMPFUN(1) = -999.
      TREST_DMPFUN(2) = +999.
      SCALE_PLOTCHI2 = 1.0  ! scale range to plot chi2

      NEARFILT_IGNORE_REST = ''

      LDMPFCN(0)     = .FALSE.
      DO ifilt    = 1, MXFILT_ALL
          DOFIT_FILT(ifilt)  = .FALSE.
          LDMPFCN(ifilt)     = .FALSE.
          LDMPFUN(ifilt)     = .FALSE.
          LDMPFCN_PLOTCHI2(ifilt)     = .FALSE.
          LDMPFUN_PLOTCHI2(ifilt)     = .FALSE.
          DOFUDGE_FITERR(ifilt)       = .FALSE.
      ENDDO

      USE_FUDGE_FITERR = .FALSE.
      FUDGE_FITERR_MAXITER   = 9
      FUDGE_FITERR_MAXFRAC   = 0.0
      FUDGE_FITERR_TREST(1)  = 999.
      FUDGE_FITERR_TREST(2)  = 999.
      FUDGE_FITERR_TREST(3)  = 999.
      FUDGE_FITERR_TREST(4)  = 999.
      FUDGE_FITERR_RESTLAM(1)  = 1000.
      FUDGE_FITERR_RESTLAM(2)  = 1000.
      FUDGE_FITERR_RESTLAM(3)  = 90000.
      FUDGE_FITERR_RESTLAM(4)  = 90000.
      FUDGE_FITERR_PASSBANDS = 'NULL'

      FUDGEALL_MAXFRAC       = 0.0
      FUDGEALL_ITER1_MAXFRAC = 0.0

      FUDGE_MAGERR_MODEL = -9.0
      FUDGE_DATAERR_SCALE = 1.0
      FUDGE_MODELERR_SCALE = 1.0

      FITCOVAR_FILE = ''

      MAGLIM_VMAX = ''
      OPT_VMAX    = 0

c -----------------------

ccc      CALL READ_DEFAULT_PRIORS ! removed Aug 13 2015

c ---------------------
c read the 'snana' namelist file for the FITINP namelist

      OPEN (
     &    UNIT   = LUNNML
     &   ,file   = nmlfile
     &   ,status = 'OLD'
     &   ,ERR    = 900
     &       )

      READ(LUNNML, NML = FITINP, ERR=901, END=902 )
      CLOSE ( UNIT = LUNNML )

      print*,' '

      CALL FITNML_OVERRIDE(IERR)

c ------------
c check legacy nml variables.
      if ( PRIOR_LUMIPAR_RANGE(1) .NE.  -9.0  ) THEN
        PRIOR_SHAPE_RANGE(1) = PRIOR_LUMIPAR_RANGE(1)
      endif
      if ( PRIOR_LUMIPAR_RANGE(2) .NE.  9.0  ) THEN
        PRIOR_SHAPE_RANGE(2) = PRIOR_LUMIPAR_RANGE(2)
      endif

      if ( PRIOR_LUMIPAR_SIGMA .NE.  0.1  ) THEN
        PRIOR_SHAPE_SIGMA = PRIOR_LUMIPAR_SIGMA
      endif

      IF ( OPT_XTMW_ERR > -8 ) THEN
         OPT_COVAR_MWXTERR = OPT_XTMW_ERR   ! Sep 22, 2013
      ENDIF
      IF ( OPT_COVAR > -98 ) THEN
         OPT_COVAR_FLUX = OPT_COVAR   ! Nov 9 2018
      ENDIF

c ------------------
c check option to turn off all priors.
      IF ( OPT_PRIOR .LE. 0 ) THEN
        OPT_PRIOR_SIMEFF       =  0
        PRIOR_AVEXP(1)         = -1.0
        PRIOR_AVEXP(2)         = -1.0
        PRIOR_SHAPE_RANGE(1)   = -8.0
        PRIOR_SHAPE_RANGE(2)   = +8.0
        PRIOR_SHAPE2_RANGE(1)   = -8.0
        PRIOR_SHAPE2_RANGE(2)   = +8.0
        PRIOR_COLOR_RANGE(1)   = -8.0
        PRIOR_COLOR_RANGE(2)   = +8.0
        PRIOR_DELTA_PROFILE(4) =  1.0
      ENDIF

      IF ( OPT_SIMEFF .NE. 0 ) THEN
         C1ERR = '&FITINP namelist variable OPT_SIMEFF is obsolete'
         C2ERR = 'Remove OPT_SIMEFF and use SIMEFF_FILE'
         CALL MADABORT('RDFITNML', C1ERR, C2ERR)
      ENDIF
c -------------------------------------
c Convert FILTLIST_XXX strings into logical arrays

      CALL PARSE_NML_FILTLISTS

c ------------------
c make a few checks
      if ( SCALE_COVAR .LE. 0.0 ) then
         USE_MODEL_MAGERR = .FALSE.
      endif

      USE_AVPRIOR = (OPT_PRIOR_AV   .GT. 0) .and.
     &              (prior_avexp(1) .GT. 0.0 )

c turn off sim efficiency code if there is no AV prior.
      if ( .not.  USE_AVPRIOR ) then
         OPT_PRIOR_SIMEFF  = 0
      endif

c check PHOTOZ stuff.

c first, allow user to set integer option or logical flag.

      if ( OPT_PHOTOZ > 0 ) then
         DOFIT_PHOTOZ = .TRUE.
      endif
      if ( DOFIT_PHOTOZ .and. OPT_PHOTOZ .LE. 0 ) then
   ! use host-galaxy prior by default.
   ! But note PRIOR_ZERRSCALE=1000 by default
         OPT_PHOTOZ = IBSET(OPT_PHOTOZ,BIT_PHOTOZ_GAUSS)
      endif

c Set non-zero step-size for PHOTOZ or DLMAG,
c depending on type of fit.

      if ( DOFIT_PHOTOZ ) THEN
         if ( INISTP_PHOTOZ < 1.0E-5 ) INISTP_PHOTOZ    = 0.05
         DOCHI2_SIGMA     = .TRUE.    ! use proper chi2 when error varies
         INTERP_OPT       = INTERP_ZSMOOTH
         if ( LAMREST_MODEL_SMOOTH .LE. 0.0 ) then
           LAMREST_MODEL_SMOOTH = 200.  ! smooth model over this lambda range
         endif

         NEVAL_MCMC_PHOTOZ = int(PARLIST_MCMC_PHOTOZ(1))
         if ( NEVAL_MCMC_PHOTOZ > 0 )  ISCALE_COURSEBIN_PHOTOZ = 0
      endif

c dump namelist to std out

      IF ( .not. REDUCE_STDOUT_BATCH ) THEN
        WRITE ( 6 , NML = FITINP )
        CALL FLUSH(6)
      ENDIF

      RETURN

c ---------------------------------------------------
900   C1ERR = 'Could not open namelist file '
      CALL MADABORT('RDFITNML', C1ERR,  nmlfile)

901   C1ERR = 'could not read &FITINP namelist from '
      CALL MADABORT('RDFITNML', C1ERR,  nmlfile)

902   C1ERR = 'Could not find &FITINP namelist in'
      CALL MADABORT('RDFITNML', C1ERR,  nmlfile)

      RETURN
      END


C =================================
CDECK  ID>,  PARSFILT. 
      SUBROUTINE PARSE_NML_FILTLISTS
c
c Created Nov 24 by R.Kessler
c Prcoess namelist strings FILTLIST_XXX and NEARFILT_IGNORE_REST,
c and fill integer arrays.
c
c Check every character to allow spaces or no spaces
c betweeh filters: i.e, 'gri' and 'g r i' are both allowed.
c
c Apr 14, 2013:
c   Allow fitting peak-mags in extra filters. For example,
c   to fit ugriz and also compute peak mags in B & V,
c      FILTLIST_FIT   = 'ugriz+BV'
c
c Apr 17 2017: check ABORT_ON_BADFILTER

c ---------------------

      IMPLICIT NONE


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )



      INTEGER
     &   i, ifilt, ifiltdef, iplus, NF
     &  ,L1, L2, N

      CHARACTER FNAM*20, ctmp*4
      LOGICAL LDEF

c function
      INTEGER FILTINDX

C --------------- BEGIN -------------

      FNAM     = 'PARSE_NML_FILTLISTS'

c --------------------------------

      DO 100 i = 1, MXFILT_ALL

        ctmp = FILTLIST_FIT(i:i)
        if ( ctmp .NE. ' ' ) then
           ifiltdef = FILTINDX(ctmp)
           if ( ifiltDEF .LE.  0 ) then
             c1err = 'Invalid FILTLIST_FIT = ' // FILTLIST_FIT
             c2err = 'Check &FITINP namelist'
             CALL MADABORT(FNAM, c1err, c2err)
           endif
           DOFIT_FILT(ifiltdef) = .TRUE.

           ifilt = IFILTDEF_INVMAP_SURVEY(ifiltdef)

           LDEF = (ifilt .GT. 0 .and. ifilt .LE. NFILTDEF_SURVEY)
           if ( (.NOT. LDEF) .and. ABORT_ON_BADFILTER ) then

              write(c1err,662) ctmp(1:1)
662           format('Fit-filter ',A,' is not a survey filter.')

              L1 = INDEX ( FILTLIST_FIT, ' ' ) - 1
              L2 = INDEX (SURVEY_FILTERS, ' ' ) - 1

              c2err = 'FILTLIST_FIT = ' // FILTLIST_FIT(1:L1) //
     &           '  but SURVEY_FILTERS = ' // SURVEY_FILTERS(1:L2)
              CALL MADABORT(FNAM, c1err, c2err)
           endif
        endif

c  skip DUMP options after 20 filters
        if ( i .GE. 20 ) GOTO 100

        ctmp = FILTLIST_DMPFCN(i:i)
        if ( ctmp .NE. ' ' ) then
           ifilt = FILTINDX(ctmp)
           if ( ifilt .LE.  0 ) then
             c1err = 'Invalid FILTLIST_DMPFCN = ' // FILTLIST_DMPFCN
             c2err = 'Check &FITINP namelist'
             CALL MADABORT(FNAM, c1err, c2err)
           endif
           if ( LPLOTCHI2 ) then
              ! either plot ...
              LDMPFCN_PLOTCHI2(ifilt) = .TRUE.
           else
              ! or stdout dump ...
              LDMPFCN(ifilt) = .TRUE.
              LDMPFCN(0)     = .TRUE.
           endif
        endif

        ctmp = FILTLIST_DMPFUN(i:i)
        if ( ctmp .NE. ' ' ) then
           ifilt = FILTINDX(ctmp)
           if ( ifilt .LE.  0 ) then
             c1err = 'Invalid FILTLIST_DMPFUN = ' // FILTLIST_DMPFUN
             c2err = 'Check &FITINP namelist'
             CALL MADABORT(FNAM, c1err, c2err)
           endif
           if ( LPLOTCHI2 ) then
              LDMPFUN_PLOTCHI2(ifilt) = .TRUE.
           else
              LDMPFUN(ifilt) = .TRUE.
           endif
        endif

        ctmp = NEARFILT_IGNORE_REST(i:i)
        if ( ctmp .NE. ' ' ) then
           ifilt = FILTINDX(ctmp)
           if ( ifilt .GT. 0 .and. ifilt .LT. MXFILT_ALL ) then
             NFILTDEF_IGNORE_REST = NFILTDEF_IGNORE_REST + 1
             N = NFILTDEF_IGNORE_REST
             ifiltdef_ignore_rest(N) = ifilt
           endif
        endif

100   CONTINUE

      RETURN
      END

C ========================================
CDECK  ID>,  FITNML_OVERRIDE. 
      SUBROUTINE FITNML_OVERRIDE(IERR)
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IERR ! (O) 0 => OK

c local var
      CHARACTER ARG*(MXCHAR_ARG), ARGLIST(MXKEY_ARGS)*(MXCHAR_ARG)
      INTEGER i, LL, ilast, iuse

      LOGICAL MATCH_NMLKEY

C -------------- BEGIN --------------

      IERR = 0

      i = 2
      ilast = 2

      DO WHILE ( i .LE. NLINE_ARGS )

        CALL GETARG(i,ARG)
        LL = INDEX ( ARG, ' ' ) - 1

        if ( MATCH_NMLKEY('FITMODEL_NAME', 1,i,ARGLIST) ) then
            FITMODEL_NAME = ARGLIST(1)

        else if ( MATCH_NMLKEY('SALT2alpha', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) SALT2alpha

        else if ( MATCH_NMLKEY('SALT2beta', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) SALT2beta

        else if ( MATCH_NMLKEY('OPT_SALT2FIT', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) OPT_SALT2FIT

        else if ( MATCH_NMLKEY('FILTLAM_SHIFT', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) FILTLAM_SHIFT

        else if ( MATCH_NMLKEY('SIMEFF_FILE', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) SIMEFF_FILE

        else if ( MATCH_NMLKEY('TREST_PEAKRENORM', 2,i,ARGLIST) ) then
            READ(ARGLIST(1),*) TREST_PEAKRENORM(1)
            READ(ARGLIST(2),*) TREST_PEAKRENORM(2)

        else if ( MATCH_NMLKEY('DELCHI2_REJECT', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) DELCHI2_REJECT

        else if ( MATCH_NMLKEY('SIGNOISE_REJECT', 1,i,ARGLIST) ) then
            READ(ARGLIST(1),*) SIGNOISE_REJECT

c --- keep legacy variables TREST_REJECT and MJD_REJECT

        else if ( MATCH_NMLKEY('TREST_REJECT', 2,i,ARGLIST) ) then
            READ(ARGLIST(1),*) TREST_REJECT(1)
            READ(ARGLIST(2),*) TREST_REJECT(2)

        else if ( MATCH_NMLKEY('MJD_REJECT', 2, i,ARGLIST) ) then
            READ(ARGLIST(1),*) MJD_REJECT(1)
            READ(ARGLIST(2),*) MJD_REJECT(2)

        else if (MATCH_NMLKEY('FITWIN_TREST_FILTER',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_TREST_FILTER

        else if ( MATCH_NMLKEY('FITWIN_TREST', 2, i, ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_TREST(1)
            READ(ARGLIST(2),*) FITWIN_TREST(2)

        else if ( MATCH_NMLKEY('FITWIN_MJD', 2, i, ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_MJD(1)
            READ(ARGLIST(2),*) FITWIN_MJD(2)

        else if ( MATCH_NMLKEY('ADD_SALT2ERR_FROMZ', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) ADD_SALT2ERR_FROMz

        else if ( MATCH_NMLKEY('ENABLE_MAGSHIFT_SALT2',
     &            1, i, ARGLIST)) then
            READ(ARGLIST(1),*) ENABLE_MAGSHIFT_SALT2
        else if ( MATCH_NMLKEY('ENABLE_WAVESHIFT_SALT2',
     &            1, i, ARGLIST)) then
            READ(ARGLIST(1),*) ENABLE_WAVESHIFT_SALT2

        else if ( MATCH_NMLKEY('ALLOW_NEGFLUX_SALT2',
     &            1, i, ARGLIST)) then
            READ(ARGLIST(1),*) ALLOW_NEGFLUX_SALT2

        else if ( MATCH_NMLKEY('USE_MODEL_MAGERR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USE_MODEL_MAGERR

        else if ( MATCH_NMLKEY('FUDGE_MAGERR_MODEL', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGE_MAGERR_MODEL

        else if ( MATCH_NMLKEY('FUDGE_DATAERR_SCALE', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGE_DATAERR_SCALE

        else if (MATCH_NMLKEY('FUDGE_MODELERR_SCALE',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGE_MODELERR_SCALE

        else if (MATCH_NMLKEY('FUDGE_FITERR_MAXFRAC',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGE_FITERR_MAXFRAC

        else if (MATCH_NMLKEY('FUDGE_FITERR_TREST', 4,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGE_FITERR_TREST(1)
            READ(ARGLIST(2),*) FUDGE_FITERR_TREST(2)
            READ(ARGLIST(3),*) FUDGE_FITERR_TREST(3)

        else if (MATCH_NMLKEY('FUDGE_FITERR_RESTLAM', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGE_FITERR_RESTLAM(1)
            READ(ARGLIST(2),*) FUDGE_FITERR_RESTLAM(2)

        else if(MATCH_NMLKEY('FUDGE_FITERR_PASSBANDS',1,i,ARGLIST)) then
            FUDGE_FITERR_PASSBANDS = ARGLIST(1)

        else if(MATCH_NMLKEY('FUDGEALL_MAXFRAC',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGEALL_MAXFRAC

        else if(MATCH_NMLKEY('FUDGEALL_ITER1_MAXFRAC',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FUDGEALL_ITER1_MAXFRAC

        else if(MATCH_NMLKEY('MAX_INTEGPDF',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) MAX_INTEGPDF

        else if ( MATCH_NMLKEY('FITWIN_PROB', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_PROB(1)
            READ(ARGLIST(2),*) FITWIN_PROB(2)

        else if ( MATCH_NMLKEY('FITWIN_NOMARG_PROB',2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_NOMARG_PROB(1)
            READ(ARGLIST(2),*) FITWIN_NOMARG_PROB(1)

        else if ( MATCH_NMLKEY('FITWIN_CHI2SIGMA', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_CHI2SIGMA(1)
            READ(ARGLIST(2),*) FITWIN_CHI2SIGMA(2)

        else if ( MATCH_NMLKEY('FITWIN_TREST', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_TREST(1)
            READ(ARGLIST(2),*) FITWIN_TREST(2)

        else if ( MATCH_NMLKEY('FITWIN_MJD', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_MJD(1)
            READ(ARGLIST(2),*) FITWIN_MJD(2)

        else if ( MATCH_NMLKEY('FITWIN_ZPULL', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_ZPULL(1)
            READ(ARGLIST(2),*) FITWIN_ZPULL(2)

        else if ( MATCH_NMLKEY('FITWIN_ZPHOT', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_ZPHOT(1)
            READ(ARGLIST(2),*) FITWIN_ZPHOT(2)

        else if ( MATCH_NMLKEY('FITWIN_SHAPE', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_SHAPE(1)
            READ(ARGLIST(2),*) FITWIN_SHAPE(2)

        else if ( MATCH_NMLKEY('FITWIN_COLOR', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_COLOR(1)
            READ(ARGLIST(2),*) FITWIN_COLOR(2)

        else if ( MATCH_NMLKEY('FITWIN_COV_OFFDIAG',2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_COV_OFFDIAG(1)
            READ(ARGLIST(2),*) FITWIN_COV_OFFDIAG(2)

        else if ( MATCH_NMLKEY('FITWIN_PEAKMJD_ERR', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_PEAKMJD_ERR(1)
            READ(ARGLIST(2),*) FITWIN_PEAKMJD_ERR(2)

        else if ( MATCH_NMLKEY('FITWIN_MB_ERR', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_MB_ERR(1)
            READ(ARGLIST(2),*) FITWIN_MB_ERR(2)

        else if ( MATCH_NMLKEY('FITWIN_SHAPE_ERR', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_SHAPE_ERR(1)
            READ(ARGLIST(2),*) FITWIN_SHAPE_ERR(2)

        else if ( MATCH_NMLKEY('FITWIN_COLOR_ERR', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_COLOR_ERR(1)
            READ(ARGLIST(2),*) FITWIN_COLOR_ERR(2)

        else if (MATCH_NMLKEY('FITWIN_PEAKMJD_ERRz1',2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_PEAKMJD_ERRz1(1)
            READ(ARGLIST(2),*) FITWIN_PEAKMJD_ERRz1(2)

        else if (MATCH_NMLKEY('FITWIN_MB_ERRz1', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_MB_ERRz1(1)
            READ(ARGLIST(2),*) FITWIN_MB_ERRz1(2)

        else if (MATCH_NMLKEY('FITWIN_SHAPE_ERRz1', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_SHAPE_ERRz1(1)
            READ(ARGLIST(2),*) FITWIN_SHAPE_ERRz1(2)

        else if (MATCH_NMLKEY('FITWIN_COLOR_ERRz1', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) FITWIN_COLOR_ERRz1(1)
            READ(ARGLIST(2),*) FITWIN_COLOR_ERRz1(2)

        else if (MATCH_NMLKEY('PRIOR_ZERRSCALE', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_ZERRSCALE

        else if (MATCH_NMLKEY('PRIOR_MUERRSCALE', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_MUERRSCALE

        else if (MATCH_NMLKEY('OPT_MNSTAT_COV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_MNSTAT_COV

        else if (MATCH_NMLKEY('OPT_PRIOR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_PRIOR

        else if (MATCH_NMLKEY('OPT_PRIOR_AV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_PRIOR_AV

        else if (MATCH_NMLKEY('OPT_PHOTOZ', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_PHOTOZ

        else if (MATCH_NMLKEY('PHOTODZ_REJECT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PHOTODZ_REJECT

        else if (MATCH_NMLKEY('PHOTODZ1Z_REJECT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PHOTODZ1Z_REJECT

        else if (MATCH_NMLKEY('PHOTOZ_ITER1_LAMRANGE',2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PHOTOZ_ITER1_LAMRANGE(1)
            READ(ARGLIST(2),*) PHOTOZ_ITER1_LAMRANGE(2)

        else if (MATCH_NMLKEY('PHOTOZ_BOUND', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PHOTOZ_BOUND(1)
            READ(ARGLIST(2),*) PHOTOZ_BOUND(2)

        else if (MATCH_NMLKEY('ISCALE_COURSEBIN_PHOTOZ',
     &              1, i, ARGLIST) ) then
            READ(ARGLIST(1),*) ISCALE_COURSEBIN_PHOTOZ

        else if (MATCH_NMLKEY('PARLIST_MCMC_PHOTOZ',5,i,ARGLIST)) then
            READ(ARGLIST(1),*) PARLIST_MCMC_PHOTOZ(1)
            READ(ARGLIST(2),*) PARLIST_MCMC_PHOTOZ(2)
            READ(ARGLIST(3),*) PARLIST_MCMC_PHOTOZ(3)
            READ(ARGLIST(4),*) PARLIST_MCMC_PHOTOZ(4)
            READ(ARGLIST(5),*) PARLIST_MCMC_PHOTOZ(5)

        else if (MATCH_NMLKEY('PRIOR_MJDSIG', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_MJDSIG

        else if (MATCH_NMLKEY('PRIOR_AVEXP', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_AVEXP(1)
            READ(ARGLIST(2),*) PRIOR_AVEXP(2)

        else if (MATCH_NMLKEY('PRIOR_AVWGT', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_AVWGT(1)
            READ(ARGLIST(2),*) PRIOR_AVWGT(2)

        else if (MATCH_NMLKEY('PRIOR_AVRES', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_AVRES

c -------- legacy --------
        else if (MATCH_NMLKEY('PRIOR_LUMIPAR_RANGE', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_LUMIPAR_RANGE(1)
            READ(ARGLIST(2),*) PRIOR_LUMIPAR_RANGE(2)

        else if (MATCH_NMLKEY('PRIOR_LUMIPAR_SIGMA', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_LUMIPAR_SIGMA
c -------------------------

        else if (MATCH_NMLKEY('PRIOR_SHAPE_RANGE', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_SHAPE_RANGE(1)
            READ(ARGLIST(2),*) PRIOR_SHAPE_RANGE(2)

        else if (MATCH_NMLKEY('PRIOR_SHAPE_SIGMA', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_SHAPE_SIGMA

c - - -
        else if (MATCH_NMLKEY('PRIOR_SHAPE2_RANGE', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_SHAPE2_RANGE(1)
            READ(ARGLIST(2),*) PRIOR_SHAPE2_RANGE(2)

        else if (MATCH_NMLKEY('PRIOR_SHAPE2_SIGMA', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_SHAPE2_SIGMA

        else if (MATCH_NMLKEY('PRIOR_DELTA_PROFILE', 4,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_DELTA_PROFILE(1)
            READ(ARGLIST(2),*) PRIOR_DELTA_PROFILE(2)
            READ(ARGLIST(3),*) PRIOR_DELTA_PROFILE(3)
            READ(ARGLIST(4),*) PRIOR_DELTA_PROFILE(4)

        else if (MATCH_NMLKEY('PRIOR_COLOR_RANGE', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_COLOR_RANGE(1)
            READ(ARGLIST(2),*) PRIOR_COLOR_RANGE(2)

        else if (MATCH_NMLKEY('PRIOR_COLOR_SIGMA', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) PRIOR_COLOR_SIGMA

        else if (MATCH_NMLKEY('NGRID_PDF', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) NGRID_PDF

        else if (MATCH_NMLKEY('NSIGMA_PDF', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) NSIGMA_PDF

        else if (MATCH_NMLKEY('OPT_COVAR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_COVAR

        else if (MATCH_NMLKEY('OPT_COVAR_FLUX', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_COVAR_FLUX

        else if (MATCH_NMLKEY('OPT_COVAR_LCFIT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_COVAR_LCFIT

        else if (MATCH_NMLKEY('OPT_COVAR_MWXTERR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_COVAR_MWXTERR

        else if (MATCH_NMLKEY('OPT_XTMW_ERR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_XTMW_ERR    ! legacy variable

        else if (MATCH_NMLKEY('SCALE_COVAR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) SCALE_COVAR

        else if (MATCH_NMLKEY('OPT_SNXT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_SNXT

        else if (MATCH_NMLKEY('OPT_NEARFILT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_NEARFILT

        else if (MATCH_NMLKEY('OPT_KCORERR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_KCORERR

        else if (MATCH_NMLKEY('ZSCALE_SIMEFF', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) ZSCALE_SIMEFF

        else if (MATCH_NMLKEY('LKCOR_AVWARP', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LKCOR_AVWARP

        else if (MATCH_NMLKEY('OPT_LANDOLT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_LANDOLT

        else if (MATCH_NMLKEY('UCOR_BXB', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) UCOR_BXB

        else if (MATCH_NMLKEY('RESTLAMBDA_FITRANGE', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) RESTLAMBDA_FITRANGE(1)
            READ(ARGLIST(2),*) RESTLAMBDA_FITRANGE(2)

        else if (MATCH_NMLKEY('UVLAM_EXTRAPFLUX', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) UVLAM_EXTRAPFLUX

        else if(MATCH_NMLKEY('SIMFIT_IDEAL_PRESCALE',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) SIMFIT_IDEAL_PRESCALE

        else if(MATCH_NMLKEY('USESIM_COLOR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_COLOR

        else if(MATCH_NMLKEY('USESIM_AV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_AV

        else if(MATCH_NMLKEY('USESIM_RV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_RV

c ------------- legacy variable
        else if(MATCH_NMLKEY('USESIM_LUMIPAR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_LUMIPAR
c -------------
        else if(MATCH_NMLKEY('USESIM_SHAPE', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_SHAPE

        else if(MATCH_NMLKEY('USESIM_PEAKMJD', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_PEAKMJD

        else if(MATCH_NMLKEY('USESIM_DLMAG', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_DLMAG

        else if(MATCH_NMLKEY('USESIM_REDSHIFT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_REDSHIFT

        else if(MATCH_NMLKEY('INIVAL_RV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_RV

        else if(MATCH_NMLKEY('INIVAL_AVRV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_AVRV

        else if(MATCH_NMLKEY('INISTP_AVRV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_AVRV

        else if(MATCH_NMLKEY('INISTP_PEAKMJD', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_PEAKMJD

        else if(MATCH_NMLKEY('INIVAL_PEAKMJD', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_PEAKMJD

        else if(MATCH_NMLKEY('INIVAL_PEAKMJD_SHIFT',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_PEAKMJD_SHIFT

        else if(MATCH_NMLKEY('INISTP_SHAPE',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_SHAPE

        else if(MATCH_NMLKEY('INISTP_DLMAG',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_DLMAG

        else if(MATCH_NMLKEY('INISTP_X0',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_X0
c
        else if(MATCH_NMLKEY('INIVAL_GRIDSEARCH_DPEAKMJD',
     &             3,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_GRIDSEARCH_DPEAKMJD(1)
            READ(ARGLIST(2),*) INIVAL_GRIDSEARCH_DPEAKMJD(2)
            READ(ARGLIST(3),*) INIVAL_GRIDSEARCH_DPEAKMJD(3)

        else if(MATCH_NMLKEY('USESIM_INIVAL', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) USESIM_INIVAL

        else if(MATCH_NMLKEY('INIVAL_GRIDSEARCH_COLOR',
     &            3,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_GRIDSEARCH_COLOR(1)
            READ(ARGLIST(2),*) INIVAL_GRIDSEARCH_COLOR(2)
            READ(ARGLIST(3),*) INIVAL_GRIDSEARCH_COLOR(3)
c
        else if(MATCH_NMLKEY('LANDOLT_COLOR_SHIFT',5,i,ARGLIST)) then
            READ(ARGLIST(1),*) LANDOLT_COLOR_SHIFT(1)  ! k0
            READ(ARGLIST(2),*) LANDOLT_COLOR_SHIFT(2)  ! k1
            READ(ARGLIST(3),*) LANDOLT_COLOR_SHIFT(3)  ! k2
            READ(ARGLIST(4),*) LANDOLT_COLOR_SHIFT(4)  ! k3
            READ(ARGLIST(5),*) LANDOLT_COLOR_SHIFT(5)  ! k4

        else if(MATCH_NMLKEY('CHECK_CRAZYFITERR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) CHECK_CRAZYFITERR

        else if(MATCH_NMLKEY('DOFIT_PHOTOZ', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) DOFIT_PHOTOZ

        else if(MATCH_NMLKEY('SKIP_PHOTOZ_INIT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) SKIP_PHOTOZ_INIT

        else if(MATCH_NMLKEY('LDMP_PHOTOZ_DROPFILTER',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LDMP_PHOTOZ_DROPFILTER

        else if(MATCH_NMLKEY('DOCHI2_SIGMA', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) DOCHI2_SIGMA

        else if(MATCH_NMLKEY('LAMREST_MODEL_SMOOTH',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LAMREST_MODEL_SMOOTH

        else if(MATCH_NMLKEY('FILTER_FITMAGDIF',1,i,ARGLIST)) then
            FILTER_FITMAGDIF = ARGLIST(1)

        else if(MATCH_NMLKEY('FILTLIST_FITRESTMAG',1,i,ARGLIST)) then
            FILTLIST_FITRESTMAG = ARGLIST(1)

        else if(MATCH_NMLKEY('LUMIFIX_FITRESTMAG',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LUMIFIX_FITRESTMAG   ! legacy

        else if(MATCH_NMLKEY('SHAPEFIX_FITRESTMAG', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) SHAPEFIX_FITRESTMAG

        else if(MATCH_NMLKEY('LAMEXTRAP_FITRESTMAG', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LAMEXTRAP_FITRESTMAG

        else if(MATCH_NMLKEY('DLAMTOL_FITRESTMAG', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) DLAMTOL_FITRESTMAG

        else if(MATCH_NMLKEY('FILTLIST_FIT', 1,i,ARGLIST)) then
            FILTLIST_FIT = ARGLIST(1)

        else if(MATCH_NMLKEY('FILTLIST_DMPFCN', 1,i,ARGLIST)) then
            FILTLIST_DMPFCN = ARGLIST(1)

        else if(MATCH_NMLKEY('FILTLIST_DMPFUN', 1,i,ARGLIST)) then
            FILTLIST_DMPFUN = ARGLIST(1)

        else if(MATCH_NMLKEY('TREST_DMPFUN', 2,i,ARGLIST)) then
            READ(ARGLIST(1),*) TREST_DMPFUN(1)
            READ(ARGLIST(2),*) TREST_DMPFUN(2)

        else if(MATCH_NMLKEY('NEARFILT_IGNORE_REST',1,i,ARGLIST)) then
            NEARFILT_IGNORE_REST = ARGLIST(1)

        else if(MATCH_NMLKEY('LTRACE',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LTRACE

        else if(MATCH_NMLKEY('LFIXPAR_ALL',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LFIXPAR_ALL

        else if(MATCH_NMLKEY('LFIXPAR_ADJUST',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LFIXPAR_ADJUST

        else if(MATCH_NMLKEY('LPLOTCHI2',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) LPLOTCHI2

        else if(MATCH_NMLKEY('IPAR_PLOTCHI2',1,i,ARGLIST)) then
            READ(ARGLIST(1),*) IPAR_PLOTCHI2

        else if(MATCH_NMLKEY('MINOS_ERRMAX_BAD', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) MINOS_ERRMAX_BAD

        else if(MATCH_NMLKEY('INIVAL_SHAPE', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_SHAPE

        else if(MATCH_NMLKEY('INISTP_SHAPE', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_SHAPE

        else if(MATCH_NMLKEY('INIVAL_SHIFT_ERRFRAC', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_SHIFT_ERRFRAC

        else if(MATCH_NMLKEY('FRACERRDIF_REPEATFIT', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) FRACERRDIF_REPEATFIT

        else if(MATCH_NMLKEY('INIVAL_AV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_AV

        else if(MATCH_NMLKEY('INISTP_AV', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_AV

        else if(MATCH_NMLKEY('INIVAL_COLOR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_COLOR

        else if(MATCH_NMLKEY('INISTP_COLOR', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_COLOR

        else if(MATCH_NMLKEY('INIVAL_X0', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_X0

        else if(MATCH_NMLKEY('INIVAL_DLMAG', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_DLMAG

        else if(MATCH_NMLKEY('INIVAL_PHOTOZ', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INIVAL_PHOTOZ

        else if(MATCH_NMLKEY('INISTP_PHOTOZ', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) INISTP_PHOTOZ

c --- Vmax

        else if(MATCH_NMLKEY('MAGLIM_VMAX', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) MAGLIM_VMAX

        else if(MATCH_NMLKEY('OPT_VMAX', 1,i,ARGLIST)) then
            READ(ARGLIST(1),*) OPT_VMAX

         endif

c set logical flag for used LINE_ARGS

         IF ( i .GT. ilast ) THEN
           DO iuse = ilast, i
              USE_LINE_ARGS(iuse) = .TRUE.
           ENDDO
         ENDIF

         i = i + 1
         ilast = i

      ENDDO

      RETURN
      END


C ==========================================
CDECK  ID>,  FINI_PARVAL. 
      SUBROUTINE FITINI_PARVAL ( iter )
c
c Init INIVAL_ and INISTP arrays.
c
c Apr 13 2020: fix INISTP[VAL]_SHAPE logic for MLCS2k2 and SNOOPY
c Jun 04 2021: if USESIM_REDSHIFT, set z errors to 1.0E-4
c
c ----------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


      INTEGER
     &   iter  ! (I) fit iteration: 1,2, ... NFIT_ITERATION

c local var

      INTEGER  NPAR, ipar, ITER_LAST
      REAL*8   PEAKMJD, VALTMP, ERRTMP
      LOGICAL  FIRST_ITER, JG

c SALT2 stuff
      REAL*8 MU, MUMIN, MUMAX, x0, X0MIN, X0MAX, mb, S2a, S2b

c functions
      REAL*8  SALT2x0calc, SALT2mBcalc  ! functions
      LOGICAL FIRST_ITERATION

C ---------- BEGIN -------------

      FIRST_ITER = FIRST_ITERATION(ITER) .and. (.not. LREPEAT_ITER)

      IF ( ITER .EQ. 1 ) THEN
         ITER_LAST = 1
      ELSE
         ITER_LAST = ITER - 1
      ENDIF

c init everything to BIDON value or to value of last iteration

      DO ipar = 1, NFITPAR_MN
        IF ( FIRST_ITER ) then
           INIVAL(ipar)       =  -9.0
           INISTP(ipar)       =   0.0
        ELSE
           VALTMP       =  FITVAL(ipar,ITER_LAST)
           ERRTMP       =  FITERR(ipar,ITER_LAST)
           INIVAL(ipar) =  VALTMP + ERRTMP*INIVAL_SHIFT_ERRFRAC
           INISTP(ipar) =  ERRTMP
        ENDIF

      ENDDO


c always modify ITERation parameter
      ipar            = IPAR_ITER
      INIVAL(IPAR)    = DBLE(iter)
      INISTP(IPAR)    = 0.0

c --------------------------------
c special code to emulate Julien's SALT2 recipe
      JG = OPT_SALT2FIT .EQ. 4  ! emulate Julien/snfit (for debug)
      if ( JG .and. ITER > 1 ) then !
           INISTP(IPAR_SHAPE) = INISTP_SHAPE  ! restore
      endif

c check special fitting options
      CALL FITRESTMAG_PREP(ITER)
      CALL FITMAGDIF_PREP(ITER)
      CALL SIMFIT_IDEAL_PREP(ITER)

c continue below on 1st iteration only.
      IF ( .NOT. FIRST_ITER ) RETURN

      SIMCHI2_CHEAT  = 0.0

      ipar           = IPAR_ISN
      INIVAL(IPAR)   = DBLE(N_SNLC_FIT+1) ! changed from ISN, Dec 2013
      INISTP(IPAR)   = 0.0

c - - -  AV - - - -
      ipar            =  IPAR_AV
      INIVAL(IPAR)    =  0.1
      INISTP(IPAR)    =  INISTP_AV
      INIBND(1,IPAR)  =  -2.0
      INIBND(2,IPAR)  =  +6.0

c - - - - RV - - - -
      ipar            =  IPAR_RV
      if ( INISTP_AVRV .GT. 0.0 ) THEN
        INIVAL(IPAR)    =  INIVAL(IPAR_AV) / RV_MWCOLORLAW
        INISTP(IPAR)    =  INISTP_AVRV
        INIBND(1,IPAR)  =  -20.0
        INIBND(2,IPAR)  =   20.0
      ELSE
        INIVAL(IPAR)    =  INIVAL_RV
        INISTP(IPAR)    =  INISTP_RV
        INIBND(1,IPAR)  =  -20.0
        INIBND(2,IPAR)  =   20.0
      ENDIF

c - - - - PKMJD - - -
      ipar            =  IPAR_PEAKMJD
      PEAKMJD         =  SNLC_SEARCH_PEAKMJD    ! approx peak MJD
      INIVAL(IPAR)    =  PEAKMJD - MJDOFF
      INISTP(IPAR)    =  INISTP_PEAKMJD         ! initial step size, days

      INIBND(1,IPAR)  =  INIVAL(IPAR) - 100.0
      INIBND(2,IPAR)  =  INIVAL(IPAR) + 100.0

      FITVAL(IPAR,0)  =  INIVAL(IPAR)

c - - - - - DLMAG - - - - -
      ipar            =  IPAR_DLMAG
      INIVAL(IPAR)    =  SNLC_DLMAG
      INISTP(IPAR)    =  INISTP_DLMAG         ! initial step size, mag
      INIBND(1,IPAR)  =   10.0   ! 7/29/2008: changed from -10,80
      INIBND(2,IPAR)  =  +70.0

      if ( USESIM_REDSHIFT ) THEN
         SNLC_REDSHIFT = SIM_REDSHIFT_HELIO + REDSHIFT_FINAL_SHIFT
         SNLC_ZHELIO   = SIM_REDSHIFT_HELIO + REDSHIFT_FINAL_SHIFT
         SNLC_ZCMB     = SIM_REDSHIFT_CMB   + REDSHIFT_FINAL_SHIFT
         SNLC_ZHD      = SIM_REDSHIFT_CMB   + REDSHIFT_FINAL_SHIFT

c  Jun 2021: set tiny z errors too
         SNLC_REDSHIFT_ERR = 1.0E-4
         SNLC_ZHELIO_ERR   = 1.0E-4
         SNLC_ZCMB_ERR     = 1.0E-4
         SNLC_ZHD_ERR      = 1.0E-4
      endif

c - - - -  zPHOT - - - - -
      ipar            =  IPAR_zPHOT
      INISTP(IPAR)    =  INISTP_PHOTOZ         ! initial step size
      INIVAL(IPAR)    =  SNLC_REDSHIFT
      INIBND(1,IPAR)  =  -1.0
      INIBND(2,IPAR)  =  +4.0

c - - - - shape/stretch - - - -
c note that INIVAL(IPAR_SHAPE,IPAR_SHAPE2) depend
c on the model and are evaluated below.
      ipar            =  IPAR_SHAPE
      INISTP(IPAR)    =  INISTP_SHAPE      ! initial step size
      INIBND(1,IPAR)  =  -20.0
      INIBND(2,IPAR)  =  +20.0

      ipar            =  IPAR_SHAPE2
      INIVAL(IPAR)    =  0.0
      INISTP(IPAR)    =  0.0
      INIBND(1,IPAR)  =  -20.0
      INIBND(2,IPAR)  =  +20.0

c -------------------------------------------
c check for valid model and set model-dependent parameters

      IF (  FITMODEL_INDEX .EQ. MODEL_STRETCH
     & .or. FITMODEL_INDEX .EQ. MODEL_STRETCH2 ) THEN

         INIVAL(IPAR_SHAPE)    =  1.0
         INIBND(1,IPAR_SHAPE)  =   0.0
         INIBND(2,IPAR_SHAPE)  =  +3.0

         IF (  FITMODEL_INDEX .EQ. MODEL_STRETCH2 ) THEN
            INIVAL(IPAR_SHAPE2)    =  1.0
            INISTP(IPAR_SHAPE2)    =  0.1
            INIBND(1,IPAR_SHAPE2)  =  0.0
            INIBND(2,IPAR_SHAPE2)  = +3.0
         ENDIF

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_MLCS2k2 ) THEN

         INIVAL(IPAR_SHAPE)    =  -0.1
         INISTP(IPAR_SHAPE)    =   0.3

         INIVAL(IPAR_COLOR)    =  INIVAL_AV
         INISTP(IPAR_COLOR)    =  INISTP_AV

c Mar 24, 2012: set bound on AV and DELTA (for photoz fit)

         INIBND(1,IPAR_COLOR) = -3.0  ! AV
         INIBND(2,IPAR_COLOR) =  5.0

         INIBND(1,IPAR_SHAPE) = -1.0  ! DELTA
         INIBND(2,IPAR_SHAPE) = +3.0

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SNOOPY ) THEN

         if (INIVAL_SHAPE==NULLVAL) INIVAL(IPAR_SHAPE) = 1.1
         INISTP(IPAR_SHAPE)    =  INISTP_SHAPE
         INIVAL(IPAR_COLOR)    =  INIVAL_AV
         INISTP(IPAR_COLOR)    =  INISTP_AV

         INIBND(1,IPAR_COLOR) =  -3.0   ! AV (July 2023)
         INIBND(2,IPAR_COLOR) =  10.0   ! extend for events like 2002cv


      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN

         if (INIVAL_SHAPE==NULLVAL) INIVAL(IPAR_SHAPE) = 0.001
         INISTP(IPAR_SHAPE)   =  INISTP_SHAPE    ! initial step size

         INIVAL(IPAR_COLOR)    =  INIVAL_COLOR
         INISTP(IPAR_COLOR)    =  INISTP_COLOR

c Dec 2023: check for M2 component
         if ( NSHAPEPAR > 1 ) then
           INISTP(IPAR_SHAPE2)   = INISTP_SHAPE2
           INIVAL(IPAR_SHAPE2)   = INIVAL_SHAPE2
           INIBND(1,IPAR_SHAPE2) = -4.0
           INIBND(2,IPAR_SHAPE2) =  4.0
         endif

c for SALT2, DLMAG is replaced by x0:

         if ( SNLC_DLMAG .GT. 0.0 ) THEN
             MU    = SNLC_DLMAG
         else
             MU  = 35.5555 ! anything to avoid NaN
         endif
         MUMIN = 20.0
         MUMAX = 70.0

c note that X08min <-> MU8MAX and vice-versa
         S2a = 0.13  ! any non-zero of alpha to avoid abort
         S2b = 3.20  ! idem for betga

         X0    = SALT2x0calc( S2a, S2b, ZERO8, ZERO8, MU )
         X0MAX = SALT2x0calc( S2a, S2b, ZERO8, ZERO8, MUMIN )
         X0MIN = SALT2x0calc( S2a, S2b, ZERO8, ZERO8, MUMAX )

         MB = SALT2mBcalc( X0 )

         IF ( OPT_SALT2FIT .EQ. 0 .or. JG) THEN
           INIVAL(IPAR_X0)    = x0
           INISTP(IPAR_X0)    = x0 * 0.1

           INIBND(1,IPAR_X0)  = x0 * 0.01
           INIBND(2,IPAR_X0)  = x0 * 100.0

           if ( JG .and. ITER .EQ. 1 ) then ! emulate Julien
              INISTP(IPAR_SHAPE) = 0.0   ! fix x1 on 1st iter
           endif

         ELSE IF ( OPT_SALT2FIT .EQ. 1 ) THEN  ! fit x0
           INIVAL(IPAR_X0)    = log10(x0)
           INISTP(IPAR_X0)    = 0.1
           INIBND(1,IPAR_X0)  = log10(x0min)
           INIBND(2,IPAR_X0)  = log10(x0max)

         ELSE IF ( OPT_SALT2FIT .EQ. 2 ) THEN  ! fit delta-mu
           INIVAL(IPAR_X0)    =   0.001   ! MUDIF
           INISTP(IPAR_X0)    =   0.1
           INIBND(1,IPAR_X0)  = -10.0
           INIBND(2,IPAR_X0)  = +10.0
         ENDIF

c if user fixes DLMAG, then fix X0.

         IF ( INISTP_DLMAG .EQ. 0.0 ) then
           INISTP(IPAR_X0) = 0.0
         ENDIF

         INIVAL(IPAR_MB) = MB
         INISTP(IPAR_MB) = 0.0

c make sure that alpha & beta are defined for photoZ fit.

         IF ( DOFIT_PHOTOZ ) THEN
           if ( SALT2alpha .EQ. -9.0 .or. SALT2beta .EQ. -9.0 ) then
             c1err = 'SALT2alpha and/or SALT2beta not defined:'
             c2err = 'these must be defined for photoZ fit'
             CALL MADABORT("FITINI_PARVAL", c1err, c2err)
           endif
         ENDIF

c set bounds on color and stretch
c Mar 24, 2012: reduce range from +-2
c Dec 5 2013: reduce max color frmo +2 to +1.
c Aug 30 2021: max color -> 2 to fit redder events

         INIBND(1,IPAR_COLOR) = -1.6  ! c
         INIBND(2,IPAR_COLOR) = +2.0

         INIBND(1,IPAR_SHAPE) = -5.0  ! x1
         INIBND(2,IPAR_SHAPE) = +5.0

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_BAYESN ) THEN
         ! May 21 2023

         INIVAL(IPAR_SHAPE)    =   0.1  ! THETA
         INISTP(IPAR_SHAPE)    =   0.1

         INIVAL(IPAR_COLOR)    =  INIVAL_AV
         INISTP(IPAR_COLOR)    =  INISTP_AV

c set bound on AV and DELTA

         INIBND(1,IPAR_COLOR) = -3.0  ! AV
         INIBND(2,IPAR_COLOR) =  5.0

         INIBND(1,IPAR_SHAPE) = -1.4  ! THETA min
         INIBND(2,IPAR_SHAPE) = +2.7  ! THETA max

      ELSE IF ( FITMODEL_INDEX .EQ. MODEL_SIMSED ) THEN

         INIVAL(IPAR_SHAPE)  =  0.0
         INISTP(IPAR_SHAPE)  =  0.0
         INIVAL(IPAR_COLOR)  =  0.0
         INISTP(IPAR_COLOR)  =  0.0

         INIVAL(IPAR_X0)    =   0.001   ! MUDIF
         INISTP(IPAR_X0)    =   0.1
         INIBND(1,IPAR_X0)  = -10.0
         INIBND(2,IPAR_X0)  = +10.0

c if user fixes DLMAG, then fix X0.
         IF ( INISTP_DLMAG .EQ. 0.0 ) then
           INISTP(IPAR_X0) = 0.0
         ENDIF

      ELSE
         write(c1err,660) FITMODEL_INDEX
660      format('Invalid FITMODEL_INDEX = ', i4 )
         CALL MADABORT("FITINI_PARVAL", c1err, "")
      ENDIF

c ------------------------

c check if user has specified any INITIAL values.
c To fix a parameter value, must also set INISTP_XXX = 0.0


      IF ( INIVAL_PEAKMJD .GT. 40000. )
     &     INIVAL_PEAKMJD = INIVAL_PEAKMJD - MJDOFF

      IF ( INIVAL_PEAKMJD .GT. NULLVAL )
     &     INIVAL(IPAR_PEAKMJD) = INIVAL_PEAKMJD

c AV & COLOR are the same parameter index;
c so allow one or the other.

      IF ( INIVAL_AV .GT. NULLVAL ) THEN
          INIVAL(IPAR_AV) = INIVAL_AV
      ELSE IF ( INIVAL_COLOR .GT. NULLVAL ) THEN
          INIVAL(IPAR_COLOR) = INIVAL_COLOR
      ENDIF

      IF ( INIVAL_RV .GT. NULLVAL .and. INISTP_AVRV .EQ. 0.0 )
     &     INIVAL(IPAR_RV) = INIVAL_RV

      IF ( INIVAL_SHAPE .GT. NULLVAL )
     &     INIVAL(IPAR_SHAPE) = INIVAL_SHAPE

      IF ( INIVAL_DLMAG .GT. NULLVAL )
     &     INIVAL(IPAR_DLMAG) = INIVAL_DLMAG

      IF ( INIVAL_PHOTOZ .GT. NULLVAL )
     &     INIVAL(IPAR_zPHOT) = INIVAL_PHOTOZ

      IF ( INIVAL_X0 .GT. NULLVAL )
     &     INIVAL(IPAR_X0) = INIVAL_X0

c May 2022: check option to set all of the INIVAL to sim-values
c    Note that fit floats all params

      IF ( USESIM_INIVAL .or. DOFIT_IDEAL ) THEN

         if ( STDOUT_UPDATE ) then
	    write(6,420) USESIM_INIVAL, DOFIT_IDEAL
420         format('   Set INIVAL = SIM value (USESIM_INIVAL=',L2,
     &           '  DOFIT_IDEAL=',L2,')' )
            call flush(6)
         endif
         INIVAL(IPAR_PEAKMJD)  = SIM_PEAKMJD
         INIVAL(IPAR_X0)       = SIM_SALT2X0
         INIVAL(IPAR_SHAPE)    = SIM_SHAPEPAR
         INIVAL(IPAR_COLOR)    = SIM_COLORPAR
         INIVAL(IPAR_zPHOT)    = SIM_REDSHIFT_HELIO
      ENDIF
c --------------------------------------------
c store SIMVAL and check option to use sim values in fit.

      IF ( LSIM_SNANA) THEN
         SIMVAL_STORE(IPAR_AV)    = SIM_COLORPAR
         SIMVAL_STORE(IPAR_RV)    = SIM_COLORLAW

         if ( INISTP_AVRV .GT. 0.0 ) then
           SIMVAL_STORE(IPAR_AVRV)  = SIM_COLORPAR/SIM_COLORLAW
         endif

         SIMVAL_STORE(IPAR_PEAKMJD) = SIM_PEAKMJD
         SIMVAL_STORE(IPAR_SHAPE)   = SIM_SHAPEPAR
         SIMVAL_STORE(IPAR_zPHOT)   = SIM_REDSHIFT_HELIO

         IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) then
            SIMVAL_STORE(IPAR_X0)   = SIM_SALT2x0
         ELSE
            SIMVAL_STORE(IPAR_DLMAG)   = SIM_DLMAG
         ENDIF

c now check if want to fix a parameter with the simulated value.

         do ipar = 1, IPAR_MAX
            if ( USESIM_FITPAR(ipar) ) then
               INIVAL(ipar) = SIMVAL_STORE(ipar)
               INISTP(ipar) = 0.0

               IF ( ipar .EQ. IPAR_PEAKMJD ) then
                  INIVAL(ipar) = INIVAL(ipar) - MJDOFF         ! Nov 2013
                  INIVAL(ipar) = INIVAL(ipar) + SHIFT_SETPKMJD ! May 2020
               ENDIF
            endif
         enddo
      ENDIF  ! end LSIM_SNANA

c --------------
c set FITVAL on 1st interation since this array
c is used in the ADJUST & FITINI_XXXX routines.
c (exception for option that fixes parameters)

      do ipar = 1, IPAR_MAX
         FITVAL(ipar,iter) = INIVAL(ipar)
         FITERR(ipar,iter) = INISTP(ipar)
      enddo

      RETURN
      END   ! end of FITINI_PARVAL


C ==========================================
CDECK  ID>,  FITINI_PHOTOZ. 
      SUBROUTINE FITINI_PHOTOZ ( iter )
c
c Created Jul 11,2006 by R.Kessler
c Used only if DOFIT_PHOTOZ=T.
c Estimate initial PHOTOZ value and fill INIVAL(IPAR_zPHOT)
c
c * if there is a valid host, then INIVAL = Zhost
c
c * if no host and 1st iteration, loop over redshift in bins
c   of 0.05 with AV=0 and LUMIPAR=0; find min CHI2.
c
c * if LREPEAT, set INIVAL = PHOTOZ from previous fit
c
c Mar 17 2018:
c  On last iteration, INIVAL += small shift to avoid crazy fit errors.
c
c Sep 25 2018:
c   INIVAL(ipar_zphot) = middle of PHOTOZ_BOUND range, not max
c    [found by R.Hounsell]
c
c Jul 12 2019
c  + call PRINT_INIPAR_ZPHOT before after course minimization
c  + call INIPAR_PHOTOZ_COURSEGRID(..)
c
c Oct 10 2019: abort if USE_SNHOST_ZPHOT=T
c
c Jan 2024: wrap Quantile debug prints under LDMP_Q flag
c --------------------------------------------
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG

c+CDE,SNFITPAR.

      INTEGER
     &   iter  ! (I) fit iteration: 1,2, ... NFIT_ITERATION

c local var

      INTEGER  IPAR, NZBIN, NCBIN, NSBIN, IPRINT, LM
      LOGICAL  LZDONE, LAST_ITER, ISMODEL_SALT2, LPRINT
      REAL*8 ZHOST, ZPHOT_LAST, ZMIN, ZMAX, z, s, c, d
      LOGICAL  LDMP_Q
      CHARACTER BANNER*60, CZTMP*20, CCID_forC*(MXCHAR_CCID)

c FCNSNLC args

      INTEGER IFLAG, q
      REAL*8
     &    GRAD(MXFITPAR)
     &   ,CHI2GUESS, CHI2END, CHI2MIN, CHI2, INIVAL_SHIFT
     &   ,ZPHOT_Q(MXZPHOT_Q), ZPHOT_PROB(MXZPHOT_Q), MEAN, STD
      CHARACTER FNAM*14
      REAL*8 GET_DIST8, USRFUN
      EXTERNAL USRFUN, init_zPDF_spline

C --------------- BEGIN -----------------

      LPRINT = STDOUT_UPDATE
      IPRINT = 0
      if (LPRINT) IPRINT = 1
      CCID_forC = SNLC_CCID(1:ISNLC_LENCCID) // char(0)

      IF ( USE_SNHOST_ZPHOT  ) THEN
         c1err = '&SNLCINP input USE_SNHOST_ZPHOT=T'
         c2err = 'not allowed with photo-z fits'
         CALL MADABORT('FITINI_PHOTOZ', c1err, c2err)
      ENDIF

      IF ( LFIXPAR_ALL  ) RETURN
      IF ( LSIM_SNANA .and. USESIM_REDSHIFT ) RETURN

      PHOTOZ_ERR_SNFIT  = -9.0
      PHOTOZ_ERR_SNHOST = -9.0
      PHOTOZ_ERR_SNMAG  = -9.0
      PHOTOZ_ERR_ZPULL  = -9.0

c set global MINUIT bound each time since it may
c get over-written in FITINI_PARVAL

      ZMIN = PHOTOZ_BOUND(1)
      ZMAX = PHOTOZ_RANGE_KCOR(2)
      ZMAX = min ( ZMAX, PHOTOZ_BOUND(2) )

c reset photoz step, unless this is a 2-band 'FITRESTMAG' fit (Nov 28, 2014)

      IPAR = IPAR_zPHOT
      if ( IFILTOBS_BRACKET(1) < 0 ) then
        INISTP(IPAR)  =  INISTP_PHOTOZ     ! initial step size
      endif

      INIBND(1,ipar)  =  ZMIN
      INIBND(2,ipar)  =  ZMAX

c Mar 27 2018:
c  on last fit iteration, move INIVAL by a small amount;
c  empirically, this reduces pathological errors on fit par.
c  Pathological error seems to be linked to starting parameters
c  at the exact chi2-minimum, so moving away from the minimum
c  seems to be the solution.
      LAST_ITER     = (ITER           .EQ. NFIT_ITERATION )
      ISMODEL_SALT2 = (FITMODEL_INDEX .EQ. MODEL_SALT2)
      IF ( LAST_ITER .and. ISMODEL_SALT2 ) THEN
        DO ipar = 1, IPAR_MAX
           if ( FLOATPAR(ipar) ) then
              INIVAL_SHIFT = INISTP(IPAR)/5.0  ! 10% of initial step
              if ( ipar == IPAR_X0 ) INIVAL_SHIFT = INIVAL(IPAR)/50.
              INIVAL(IPAR) = INIVAL(IPAR) + INIVAL_SHIFT
           endif
        ENDDO
      ENDIF


c continue processing only on 1st fit iteration,
      IF ( LREPEAT_ITER  ) RETURN
      IF ( ITER > 1      ) RETURN

      IF ( LPRINT) THEN
         write(BANNER,10) SNLC_CCID(1:ISNLC_LENCCID)
10       format('FITINI_PHOTOZ for CID=',A )
         CALL PRBANNER ( BANNER )
      endif

c --------------------------------------------


c ----------------------------------------
c set initial value and step size.

      Zhost     =  SNHOST_ZPHOT(1)
      LZDONE    = .FALSE.

      IF ( BTEST(OPT_PHOTOZ,BIT_BESTZ_GAUSS) ) THEN  ! Zspec prior
        INIVAL(ipar) = SNLC_REDSHIFT
        LZDONE       = .TRUE.
        CZTMP        = 'REDSHIFT_FINAL'

c Jan 2021: if user has not specified PRIOR_ZERRSCALE, then set it to 1
        if ( PRIOR_ZERRSCALE == 1000.0 )  PRIOR_ZERRSCALE = 1.0
        PHOTODZ_REJECT   = SNLC_REDSHIFT_ERR
c xxx mark delete        PHOTOZ_ITER1_LAMRANGE(1) =  2000.

        goto 777        ! Jan 2021

      ELSE IF ( BTEST(OPT_PHOTOZ,BIT_PHOTOZ_GAUSS) ) THEN  ! Zhost prior (1)

        if ( DOFIT_PHOTOZ_HOST ) THEN
           INIVAL(ipar) = Zhost
           LZDONE       = .TRUE.
           CZTMP        = 'Zhost'
        else
           CZTMP        = 'AVG[PHOTOZ_BOUND]'
           INIVAL(IPAR) = (PHOTOZ_BOUND(2) + PHOTOZ_BOUND(1))/2.0
           IF( SKIP_PHOTOZ_INIT ) GOTO 888
        endif

      ELSE IF ( BTEST(OPT_PHOTOZ,BIT_PHOTOZ_QUANTILES) ) THEN ! R.Chen Jun 2022

         LDMP_Q = .false.  ! RK - control debug dump with  flag

        if ( LDMP_Q ) then
            Print *, ' xxx Start prep for init_zPDF_quantile'
        endif
        if ( SNHOST_NZPHOT_Q .le. 0 ) THEN
            c1err = 'zPDF quantiles requested for photo-z fit'
            c2err = 'but there are no zPDF quantiles in the data.'
            CALL MADABORT("FITINI_PHOTOZ", c1err, c2err)
        endif
        do q = 1, SNHOST_NZPHOT_Q
            ZPHOT_PROB(q) = DBLE(SNHOST_ZPHOT_PERCENTILE(q))/100.
            ZPHOT_Q(q)    = DBLE(SNHOST_ZPHOT_Q(1,q))
            if ( LDMP_Q ) THEN
              print*,' xxx   PROB=', sngl(ZPHOT_PROB(q)),
     &                ' for ZPHOT=', sngl(ZPHOT_Q(q))
              call flush(6)
            endif
        enddo

        LM = INDEX(METHOD_SPLINE_QUANTILES,' ') - 1
        CALL init_zPDF_spline(SNHOST_NZPHOT_Q, ZPHOT_PROB, ZPHOT_Q,
     &     CCID_forC, METHOD_SPLINE_QUANTILES(1:LM)//char(0),
     &     IPRINT, MEAN, STD,ISNLC_LENCCID, 20)

        SNHOST_QZPHOT_MEAN(1) = MEAN ! store mean & std in 4 byte global
        SNHOST_QZPHOT_STD(1)  = STD

        if ( LDMP_Q ) then
           Print *, ' xxx Finished init_zPDF_spline'
           call flush(6)
        endif

c     initialize at Q50
          INIVAL(ipar) = SNHOST_ZPHOT_Q(1,6)
          LZDONE       = .TRUE.
          CZTMP        = 'ZPHOT_Q50'
      ENDIF

c check cheat option (4/30/2012)
      IF ( DOFIT_PHOTOZ_CHEAT ) THEN  ! cheat option
        CZTMP        = 'Z(Cheat)'
        INIVAL(ipar) = SNLC_REDSHIFT
        LZDONE       = .TRUE.
      ENDIF


c -------------------------------------------------
c if we get here, then we have just the SN with no hostZ to lean on;
c search course grid to find min chi2.

      IFLAG   = FCNFLAG_USER  ! flag for FCNSNLC
      DOFIT_PHOTOZ_MCMC_ADJUST =
     &     ( NEVAL_MCMC_PHOTOZ > 0 .and. (.not. LZDONE) )

c -----------------------------------------------------
c call FCNSNLC with INIVAL and IFLAG = FCNFLAG_USER (last-call)
c to set EP_XXX arrays with initial conditions.
c This is needed to check initial data/model normalization.

c open up the x0 bound for the course grid search (Feb 4, 2014)
      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
         INIBND(1,IPAR_X0) = 1.0E-15
         INIBND(2,IPAR_X0) = 10000.
      ENDIF

c Use initial guess to get starting CHI2GUESS
      z       = INIVAL(IPAR_zPHOT)
      s       = INIVAL(IPAR_SHAPE)
      c       = INIVAL(IPAR_COLOR)
      d       = GET_DIST8(Z,s,c,ONE8);
      INIVAL(IPAR_DLMAG) = d
      if ( DOFIT_PHOTOZ_MCMC_ADJUST ) then
         INIVAL(IPAR_SPARE) = 0.0
      else
         INIVAL(IPAR_SPARE) = 1.0
      endif
      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2GUESS,INIVAL,IFLAG,USRFUN)
      if(LPRINT) CALL PRINT_INIPAR_ZPHOT('guess',INIVAL,CHI2GUESS)

c - - - - - -
      if ( DOFIT_PHOTOZ_MCMC_ADJUST ) then
         CALL INIPAR_PHOTOZ_MCMC(CHI2GUESS)
      else
         CALL INIPAR_PHOTOZ_COURSEGRID(CHI2GUESS,LZDONE)
      endif

 444  CONTINUE

c update x0-bound for SALT2
      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
         d = INIVAL(IPAR_DLMAG)
         INIBND(1,IPAR_X0) = 0.01  * d
         INIBND(2,IPAR_X0) = 100.  * d
      ENDIF

      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2,INIVAL,IFLAG,USRFUN)

777   CONTINUE
      if(LPRINT) CALL PRINT_INIPAR_ZPHOT('eval', INIVAL, chi2)

      CALL FLUSH(6)

888   CONTINUE

      REDSHIFT_FIT = INIVAL(IPAR_zPHOT)

      RETURN
      END   ! end of FITINI_PHOTOZ

C =============================
CDECK  ID>,  PRINT_INIPAR_ZPHOT. 
      SUBROUTINE PRINT_INIPAR_ZPHOT(string,INIPAR_VAL,chi2)
c Created July 2012
c FITINI_PHOTOZ print utility to show
c     initial-[string]: zPhot,s,c,x0 = [values]

c local var

      IMPLICIT NONE
      CHARACTER STRING*(*)                 ! (I) descriptor
      REAL*8 INIPAR_VAL(*),     chi2   ! (I) values to print


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      REAL*8  z, s, c, x0, d
      INTEGER LZ, LS, LC, LD, LD2
      LOGICAL LEGACY
      CHARACTER PARNAME_D*20

C ----------- BEGIN --------

      IF ( .not. STDOUT_UPDATE ) RETURN

      LEGACY  = (NEVAL_MCMC_PHOTOZ .EQ. 0)  ! legacy = course grid
      IF ( LEGACY ) THEN
         PARNAME_D = 'dScale'  ! course grid (legacy)
      ELSE
         PARNAME_D = 'dmu'   ! MCMC
      ENDIF

      LZ  = INDEX(PARNAME_STORE(IPAR_zPHOT),  ' ' ) - 1
      LS  = INDEX(PARNAME_STORE(IPAR_SHAPE),  ' ' ) - 1
      LC  = INDEX(PARNAME_STORE(IPAR_COLOR),  ' ' ) - 1
      LD  = INDEX(PARNAME_STORE(IPAR_DLMAG),  ' ' ) - 1
      LD2 = INDEX(PARNAME_D,                  ' ' ) - 1

      z       = INIPAR_VAL(IPAR_zPHOT)
      s       = INIPAR_VAL(IPAR_SHAPE)
      c       = INIPAR_VAL(IPAR_COLOR)
      x0      = INIPAR_VAL(IPAR_DLMAG)
      d       = INIPAR_VAL(IPAR_SPARE)

      write(6,43) STRING
     &     ,PARNAME_STORE(IPAR_zPHOT)(1:LZ)
     &     ,PARNAME_STORE(IPAR_SHAPE)(1:LS)
     &     ,PARNAME_STORE(IPAR_COLOR)(1:LC)
     &     ,PARNAME_STORE(IPAR_DLMAG)(1:LD)
     &     ,PARNAME_D(1:LD2)
     &     ,z, s, c, x0, d

 43   format(T5,'initial-',A, 2x,
     &         5(A,1x),'= ', 3F7.3, 1x, G8.2, 1x, F6.3 )

      write(6,44) STRING, CHI2
 44   format(T5,'initial-',A, 2x, 'CHI2 = ',G12.4 )

      CALL FLUSH(6)

      RETURN
      END

C ====================================
CDECK  ID>,  INIPAR_PHOTOZ_COURSEGRID. 
      SUBROUTINE INIPAR_PHOTOZ_COURSEGRID(CHI2INI,LZFIX)

c Created July 12 2019
c Estimate initial photo-z parameters using course grid.
c [Code moved from FITINI_PHOTOZ]

      IMPLICIT NONE

c subroutine arguments
      REAL*8  CHI2INI ! (I) initial chi2 from guess; try doing better
      LOGICAL LZFIX   ! (I) T=> fix redshift to INIVAL

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      REAL*8 Z_SAVE, ZMIN, ZMAX, ZBIN, z
      REAL*8 S_SAVE, SMIN, SMAX, SBIN, s
      REAL*8 C_SAVE, CMIN, CMAX, CBIN, c
      REAL*8 Fmodel_SCALE, Fmodel_SCALE_SAVE, d, d_SAVE
      REAL*8 GRAD(MXFITPAR), CHI2, CHI2MIN
      INTEGER NZBIN, NSBIN, NCBIN, iz, is, ic, IFLAG, ITER

      REAL*8 GET_DIST8, USRFUN
      EXTERNAL USRFUN

C ------------- BEGIN ------------

      ITER  = 1
      IFLAG = FCNFLAG_USER  ! to fill EP_XXX arrays in FCNSNLC

      IF ( ISCALE_COURSEBIN_PHOTOZ .LE. 0 ) THEN
         write(c1err,661) ISCALE_COURSEBIN_PHOTOZ
661      format('Invalid ISCALE_COURSEBIN_PHOTOZ = ', I6)
         c2err = 'Check  &FITINP namelist'
         CALL MADABORT("FITINI_PARVAL", c1err, c2err)
      ENDIF


      CHI2MIN = CHI2INI
      Z_SAVE  = INIVAL(IPAR_zPHOT)
      D_SAVE  = INIVAL(IPAR_DLMAG)  ! mu or x0 (distance par)
      C_SAVE  = INIVAL(IPAR_COLOR)  ! AV or c
      S_SAVE  = INIVAL(IPAR_SHAPE)   ! stretch (x1, delta...)

c loop over redshift, color, stretch to estimate INIVAL

      IF ( LZFIX ) THEN
        ZMIN = Z_SAVE
        ZMAX = Z_SAVE
      ELSE
        ZMIN  = INIBND(1,IPAR_zPHOT)
        ZMAX  = INIBND(2,IPAR_zPHOT)
      ENDIF
      NZBIN = ISCALE_COURSEBIN_PHOTOZ * int(25.*(ZMAX-ZMIN)) + 1
      ZBIN  = (ZMAX - ZMIN) / DBLE(NZBIN)

      CALL SETBINS_FITINI_PHOTOZ(IPAR_COLOR,   ITER,
     &                 NCBIN,CBIN,CMIN,CMAX)  ! output
      CALL SETBINS_FITINI_PHOTOZ(IPAR_SHAPE, ITER,
     &                 NSBIN,SBIN,SMIN,SMAX)  ! output

      IF ( STDOUT_UPDATE ) THEN
         print*,'    Course-grid minimization for initial values: '
         write(6,432) NZBIN, 'photoz', ZMIN, ZMAX, ZBIN
         write(6,432) NCBIN, 'color ', CMIN, CMAX, CBIN
         write(6,432) NSBIN, 'shape ', SMIN, SMAX, SBIN
         call flush(6)
 432     format(T10,I3, 2x, A,' bins from ', F8.3,' to ', F8.3,
     &        3x,'(binsize=',F7.3,')'  )
      ENDIF

      DO 55 iz  = 1, NZBIN
        z  = ZMIN + dble(iz-1)*ZBIN
        INIVAL(IPAR_zPHOT) = Z

      DO 57 is = 1, NSBIN
        s = SMIN + dble(is-1) * SBIN
        INIVAL(IPAR_SHAPE) = s

      DO 59 ic  = 1, NCBIN
        c       = CMIN + dble(ic-1)*CBIN
        INIVAL(IPAR_COLOR)  = c

        d       = GET_DIST8(Z,s,c,ONE8)
        INIVAL(IPAR_DLMAG)  = d

c call function to evaluate R4SN_XXX variables needed to
c determine Fmodel_SCALE below.
        CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2,INIVAL,IFLAG,USRFUN)

c now compute Fmodel_SCALE to minimize chi2 as a function of
c x0 or MU. This is an approximation assuming that the error-squared
c is constant, but it really depends slightly on the Fmodel_SCALE value.

        IF ( R4SN_FFSUM_CROSS > 0 .and. R4SN_FFSUM_MODEL > 0 ) then
           Fmodel_SCALE        = R4SN_FFSUM_CROSS/R4SN_FFSUM_MODEL
        ELSE
           Fmodel_SCALE        = 1.0  ! June 30 2013
        ENDIF

        d                   = GET_DIST8(Z,s,c,Fmodel_SCALE)
        INIVAL(IPAR_DLMAG)  = d
        CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2,INIVAL,IFLAG,USRFUN)

c ------------
        if ( chi2 < -1300.  ) then
          write(6,667) z, PARNAME_STORE(IPAR_COLOR)(1:3),
     &                 c,s,d,chi2, Fmodel_SCALE
667       format(' xxxx Z=',F5.3, 2x, A,'=',F6.3, 2x,
     &           's=',F6.3, 2x, 'DIST=',G8.3, 2x, 'CHI2=',E10.3,
     &           2x, 'Fscale=',G8.3 )
          call flush(6)
cc          STOP ! xxxxxxxx
        endif
c -------
        if ( CHI2 .LT. CHI2MIN ) then
            chi2min = chi2
            Z_SAVE = INIVAL(IPAR_zPHOT)
            C_SAVE = INIVAL(IPAR_COLOR)
            S_SAVE = INIVAL(IPAR_SHAPE)
            D_SAVE = INIVAL(IPAR_DLMAG)
            Fmodel_SCALE_SAVE = Fmodel_SCALE
        endif

59    CONTINUE  ! color
57    CONTINUE  ! lumipar
55    CONTINUE  ! photoz

c load inital redshift and re-run FCNSNLC to update EP_FLUX_MODEL

      INIVAL(IPAR_zPHOT)   = Z_SAVE  ! save redshift
      INIVAL(IPAR_COLOR)   = C_SAVE  ! save color
      INIVAL(IPAR_DLMAG)   = D_SAVE  ! save distance
      INIVAL(IPAR_SHAPE)   = S_SAVE  ! save lumi/shape param
      INIVAL(IPAR_SPARE)   = Fmodel_SCALE_SAVE

      RETURN
      END     ! end INIPAR_PHOTOZ_COURSEGRID


C ====================================================
CDECK  ID>,  INIPAR_PHOTOZ_MCMC. 
      SUBROUTINE INIPAR_PHOTOZ_MCMC(CHI2INI)
c Created Jul 2019
c Estimate initial all 5 photo-z params using MCMC  method.
c The goal is to significantly reduce init time compared with
c the COURSEGRID method, and maybe even do a better job.
c Works only for SALT2 model.
c
c   !!! BEWARE: this is experimental !!!
c -------------------------------
      IMPLICIT NONE

c subroutine args
      REAL*8 CHI2INI  ! (I) chi2 from guess params; goal is to beat this

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER ISEED
      PARAMETER ( ISEED = 12379 )

      INTEGER NEVAL_REDUCE_STEP
      REAL*8  FRACRANGE_STEPINI, FRAC_STEP_REDUCE, DMU_MAX

      INTEGER IFLAG, NTMP, itry, NPAR, i, IPAR, IPAR_LIST(MXFITPAR)
      REAL*8 CHI2min, DIF, AVG, STEP, VAL, ran
      REAL*8 z,s,c,t0,d, dmu, x0cosmo, x0
      REAL*8 CHI2, CHI2_LAST, ARG, PROB, VALMIN, VALMAX
      REAL*8 MCMC_STEPVAL(MXFITPAR), MCMC_TRYVAL(MXFITPAR)
      REAL*8 GRAD(MXFITPAR), BND_LOCAL(2,MXFITPAR)
      REAL*8 INIVAL_SAVE(MXFITPAR)
      LOGICAL MOVE
      LOGICAL LDMP / .FALSE. /
      CHARACTER PARNAME*20

c function
      REAL*8 GET_DIST8, USRFUN
      EXTERNAL USRFUN

C ------------ BEGIN ----------

      CALL SRAND(ISEED)
      IFLAG   = FCNFLAG_USER
      CHI2MIN = CHI2INI
      NTMP    = 0

cc    NEVAL_MCMC_PHOTOZ = int(PARLIST_MCMC_PHOTOZ(1)) ! already done
      NEVAL_REDUCE_STEP = int(PARLIST_MCMC_PHOTOZ(2))
      FRACRANGE_STEPINI = PARLIST_MCMC_PHOTOZ(3)
      FRAC_STEP_REDUCE  = PARLIST_MCMC_PHOTOZ(4)
      DMU_MAX           = PARLIST_MCMC_PHOTOZ(5)

      IF ( STDOUT_UPDATE ) THEN
         write(6,30) 'Use MCMC minimization for initial values: '
 30      format(T7,A)
         write(6,31) NEVAL_MCMC_PHOTOZ, FRAC_STEP_REDUCE,
     &               NEVAL_REDUCE_STEP
 31      format(T7,I3,' evals, STEP*=',F4.2,' every ',I3,' evals.')
         write(6,32) FRACRANGE_STEPINI
 32      format(T7,'Initial MCMC STEP = RANGE x ', F5.2 )
      ENDIF

      NPAR         = 5
      IPAR_LIST(1) = IPAR_ZPHOT
      IPAR_LIST(2) = IPAR_SHAPE
      IPAR_LIST(3) = IPAR_COLOR
      IPAR_LIST(4) = IPAR_PEAKMJD
      IPAR_LIST(5) = IPAR_DLMAG

      BND_LOCAL(1,IPAR_ZPHOT)   = INIBND(1,IPAR_ZPHOT)
      BND_LOCAL(2,IPAR_ZPHOT)   = INIBND(2,IPAR_ZPHOT)
      BND_LOCAL(1,IPAR_SHAPE)   = -3.0  ! x1 min
      BND_LOCAL(2,IPAR_SHAPE)   = +3.0  ! x1 max
      BND_LOCAL(1,IPAR_COLOR)   = -0.2  ! c min
      BND_LOCAL(2,IPAR_COLOR  ) =  0.4  ! c max
      BND_LOCAL(1,IPAR_PEAKMJD) = SNLC_SEARCH_PEAKMJD - 7.0
      BND_LOCAL(2,IPAR_PEAKMJD) = SNLC_SEARCH_PEAKMJD + 7.0
      BND_LOCAL(1,IPAR_DLMAG) = -DMU_MAX  ! MU shift w.r.t. cosmo constraint
      BND_LOCAL(2,IPAR_DLMAG) = +DMU_MAX

c for each param, get initial start value and step size
      DO i = 1, NPAR
         IPAR = IPAR_LIST(i)
         DIF  = (BND_LOCAL(2,IPAR) - BND_LOCAL(1,IPAR))
         AVG  = (BND_LOCAL(2,IPAR) + BND_LOCAL(1,IPAR))/2.0
         STEP = DIF * FRACRANGE_STEPINI
         MCMC_STEPVAL(IPAR) = STEP
         MCMC_TRYVAL(IPAR)  = AVG
         INIVAL(IPAR)       = AVG
         PARNAME            = PARNAME_STORE(IPAR)
         if ( IPAR == IPAR_DLMAG ) PARNAME = 'dmu'

         if ( STDOUT_UPDATE ) then
            write(6,60) PARNAME, AVG, STEP
 60         format(T7,'Start ', A6,' value/step: ', F9.3,'/', F6.3 )
            call flush(6)
         endif
      ENDDO


      z = INIVAL(IPAR_ZPHOT);
      s = INIVAL(IPAR_SHAPE);
      c = INIVAL(IPAR_COLOR)
      INIVAL(IPAR_DLMAG) = GET_DIST8(z,s,c,ONE8)
      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2,INIVAL,IFLAG,USRFUN)
      CHI2_LAST = CHI2

c store initial chi2min in case we don't find better
      CHI2MIN = CHI2
      DO i = 1, NPAR
         IPAR = IPAR_LIST(i)
         INIVAL_SAVE(IPAR) = INIVAL(IPAR)
      ENDDO
      INIVAL_SAVE(IPAR_SPARE) = 0.0  ! dmu from cosmology constraint

c - - - - - - - - - - -

      DO 50 itry = 1, NEVAL_MCMC_PHOTOZ

         DO 51 i = 1, NPAR
            IPAR   = IPAR_LIST(i)
            ran    = rand()-0.5    ! between -0.5 and +0.5
            STEP   = MCMC_STEPVAL(IPAR)
            VAL    = MCMC_TRYVAL(IPAR) + (STEP*ran)
            VALMIN = BND_LOCAL(1,IPAR)
            VALMAX = BND_LOCAL(2,IPAR)
            ! respect bounds
            if ( VAL < VALMIN ) VAL = VALMIN + STEP/20.0
            if ( VAL > VALMAX ) VAL = VALMAX - STEP/20.0
            INIVAL(IPAR) = VAL
            if ( IPAR == IPAR_DLMAG ) dmu = VAL
 51      CONTINUE

c treat x0/mu a bit different
         z       = INIVAL(IPAR_ZPHOT)
         s       = INIVAL(IPAR_SHAPE)
         c       = INIVAL(IPAR_COLOR)
         t0      = INIVAL(IPAR_PEAKMJD)
         x0cosmo = GET_DIST8(z,s,c,ONE8)
         x0      = x0cosmo * 10**(-0.4*dmu)
         INIVAL(IPAR_DLMAG) = x0  ! overwrite dmu with x0

c call function to evaluate chi2 for this INIVAL trial
         CALL FCNSNLC(NFITPAR_MN,GRAD,CHI2,INIVAL,IFLAG,USRFUN)

         ARG  = -(CHI2-CHI2_LAST)/2.0
         PROB = EXP(ARG)
         IF ( PROB > 1.0 ) PROB = 1.0
         MOVE = .FALSE.
         if ( RAND() < PROB ) then
            MOVE = .TRUE.
            DO i = 1, NPAR
               IPAR = IPAR_LIST(i)
               MCMC_TRYVAL(IPAR) = INIVAL(IPAR)
            ENDDO
         endif

         if ( CHI2 < CHI2MIN ) then
            CHI2MIN = CHI2
            DO i = 1, NPAR
               IPAR = IPAR_LIST(i)
               INIVAL_SAVE(IPAR) = INIVAL(IPAR)
            ENDDO
            INIVAL_SAVE(IPAR_SPARE) = dmu
         endif

         NTMP = NTMP + 1
         if ( NTMP == NEVAL_REDUCE_STEP  ) then
c reduce step size, and move to current values with min chi2
            NTMP = 0
            DO i = 1, NPAR
               IPAR = IPAR_LIST(i)
               MCMC_STEPVAL(ipar) = MCMC_STEPVAL(ipar)*FRAC_STEP_REDUCE
               MCMC_TRYVAL(ipar)  = INIVAL_SAVE(ipar)
            ENDDO
         endif

            if ( LDMP ) then
               print*,' xxx --------------------------------------- '
               write(6,665) z, s, c, t0
               write(6,666) itry, CHI2,CHI2_LAST, PROB, MOVE
               call flush(6)
 665           format('  xxx z, s, c, PKMJD = ', 3F7.3, F11.3 )
 666           format('  xxx itry=',I3, 2x, 'CHI2(cur,last)=',2F6.0, 2x,
     &              'PROB=',F6.3, 2x, 'MOVE=',L2)
            endif

         CHI2_LAST = CHI2
 50   CONTINUE

c restore INIVAL_SAVE at mon chi2 to global INIVAL
      DO i = 1, NPAR
         IPAR = IPAR_LIST(i)
         INIVAL(IPAR) = INIVAL_SAVE(IPAR)
      ENDDO
      INIVAL(IPAR_SPARE) = INIVAL_SAVE(IPAR_SPARE)

      RETURN
      END      ! INIPAR_PHOTOZ_MCMC

C ====================================================
CDECK  ID>,  STBINZPH. 
      SUBROUTINE SETBINS_FITINI_PHOTOZ(IPAR,ITER,
     &                                 NBIN,PARBIN,PARMIN,PARMAX)
c
c Created March 25, 2012 by R.Kessler
c
c Call by FITINI_PHOTOZ to set color (IPAR=IPAR_COLOR) or
c stretch (IPAR=IPAR_SHAPE) bins. These bins are used
c to loop over a course grid to find an approx. global min.
c
c July 5 2019: min color bound -> -0.2 (was -0.3)
c
c ---------------------

      IMPLICIT NONE

c subroutine args.
      INTEGER IPAR                  ! (I) fit parameter index
      INTEGER ITER                  ! (I) fit-iteration to prepare
      INTEGER NBIN                  ! (O) Number of bins
      REAL*8  PARBIN,PARMIN,PARMAX  ! (O) binsize, min and max

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      LOGICAL DO_SALT2, DO_COLOR, DO_SHAPE
      REAL*8 PARLAST, DIF, BND_LOCAL(2)

C --------------- BEGIN ---------------

c define local bound to be tighter than INIBND since
c INIBND is larger than we need.

      DIF = INIBND(2,IPAR) - INIBND(1,IPAR)
      BND_LOCAL(1) = INIBND(1,IPAR) + 0.2*DIF
      BND_LOCAL(2) = INIBND(2,IPAR) - 0.2*DIF

c hard-code color range for SALT2 model (Dec 2014)
      DO_SALT2 = ( FITMODEL_INDEX .EQ. MODEL_SALT2 )
      DO_COLOR = ( IPAR == IPAR_COLOR )
      DO_SHAPE = ( IPAR == IPAR_SHAPE )

      IF ( DO_SALT2 .and. DO_COLOR ) THEN
        BND_LOCAL(1) = -0.2  ! -0.3 -> -0.2 (July 3 2019)
        BND_LOCAL(2) = +0.4
      ENDIF

c --------------------------------------------

      IF ( INISTP(IPAR) .EQ. 0.0 ) THEN ! fixed parameter
        NBIN    = 1
        PARMIN  = INIVAL(IPAR)
        PARMAX  = INIVAL(IPAR)
        PARBIN  = 0.0

      ELSE
        PARMIN  = BND_LOCAL(1)
        PARMAX  = BND_LOCAL(2)
        IF ( DO_COLOR ) THEN
           NBIN    = int(6.*(PARMAX-PARMIN) ) + 1     ! hard-wire
        ELSE
           NBIN    = 3  ! stretch/lumi bins
        ENDIF

        NBIN = NBIN * ISCALE_COURSEBIN_PHOTOZ

        PARBIN  = (PARMAX - PARMIN) / DBLE(NBIN)
      ENDIF


      RETURN
      END    ! end SETBINS_FITINI_PHOTOZ

C ==========================================
CDECK  ID>,  FINI_ADJUST. 
      SUBROUTINE FITINI_ADJUST ( iter )
c
c Re-Created April 6, 2009 by R.Kessler
c
c Compute data/model ratio and adjust either MU or x0
c so that initial model matches data better.
c This is much simpler than original version.
c
c Aug 30 2017: use function FIRST_ITERATION instead of test on ITER.
c              --> accomodate SIMFIT_IDEAL logic
c
c Mar 4 2020
c  + modify PKMJD sweep from -2, 2 in 1 day bins, to -4 to +4 in 2 day bins.
c  + remove CHI2TEST on 5*NEPOCH
c
c Aug 4 2021
c  + add optional color grid search with INIVAL_GRIDSEARCH_COLOR - D. Jones
c ----------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


      INTEGER
     &   iter  ! (I) fit iteration: 1,2, ... NFIT_ITERATION

c local var

      INTEGER
     &   CID, IFILT, IFILT_OBS, NFILT, LTMP, i, ipar
     &  ,IPAR_ADJUST, NF, NZ, LCHAR, LCHAR2

      LOGICAL LPRINT
      LOGICAL LZFIT, FIRST_ITER, DO_PEAKMJD, DO_COLOR
      CHARACTER BANNER*60, CFILT*(MXFILT_ALL), cpar*20

      REAL
     &   RATIO_FLUX(MXFILT_ALL), RATIO_FLUX_AVG, rflux, CHI2, Xsig, ZTMP
     &  ,PEAKMJD_INI, PEAKMJD_SAVE
     &  ,DIFMJD_MIN, DIFMJD_MAX, DIFMJD_BIN, DIFMJD
     &  ,COLOR_INI, COLOR_SAVE, COLOR_MIN, COLOR_MAX, COLOR_BIN, COLOR
     &  ,PHOTOZ_INI, PHOTOZ_SAVE, PHOTOZ_STP
     &  ,INIVAL_START(IPAR_MAX), RTMP(MXFILT_ALL)

      REAL*8  T8, Z8

c FCNSNLC args
      INTEGER IFLAG
      REAL*8 GRAD(MXFITPAR), CHI8INI, CHI8END, CHI8MIN, CHI8, CHI8TEST

c functions
      REAL  DATA_MODEL_RATIO
      REAL*8  USRFUN
      EXTERNAL USRFUN
      LOGICAL  FIRST_ITERATION

C --------------- BEGIN -------------

      if ( DOFIT_PHOTOZ_MCMC_ADJUST ) RETURN

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 0")

c process only 1st fit iteration

      FIRST_ITER = FIRST_ITERATION(ITER)

      IF ( .NOT. FIRST_ITER ) RETURN
      IF ( LFIXPAR_ALL      ) RETURN
      IF ( USESIM_INIVAL    ) RETURN  ! May 2022
      IF ( DOFIT_IDEAL      ) RETURN  ! Dec 2023

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 1")

      LPRINT = STDOUT_UPDATE


c init everything to zero

      DO ifilt_obs = 1, MXFILT_ALL
         RATIO_FLUX(ifilt_obs)   = -9.0
      ENDDO


      cid   = SNLC_CID
      Z8    = REDSHIFT_FIT

      IFLAG = FCNFLAG_USER  ! to fill EP_XXX arrays in FCNSNLC

      IF ( LPRINT ) THEN
         LCHAR = ISNLC_LENCCID
         write(BANNER,10) cid, SNLC_CCID(1:LCHAR)
10       format('FITINI_ADJUST for CID=',I8, 3x, '(',A,')'   )
         CALL PRBANNER ( BANNER )
      endif

c save initial values before they are modified

      DO ipar = 1, IPAR_MAX
        INIVAL_START(ipar) = INIVAL(ipar)
      ENDDO

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 2")

c -----------------------------------------------------
c call FCNSNLC with INIVAL and IFLAG = FCNFLAG_USER (last-call)
c to set EP_XXX arrays with initial conditions.
c This is needed to check initial data/model normalization.

      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI8INI,INIVAL,IFLAG,USRFUN)

      if ( LPRINT ) then
        write(6,56) 'BEFORE', chi8INI, NEPOCH_ALL(0)
      endif

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 3")

c -----------------------------------------------------
c Now check PEAKMJD by testing 1/2-sigma steps

442   CONTINUE

      PEAKMJD_INI  = INIVAL(IPAR_PEAKMJD)
      PEAKMJD_SAVE = INIVAL(IPAR_PEAKMJD)
      DIFMJD_MIN   = INIVAL_GRIDSEARCH_DPEAKMJD(1)
      DIFMJD_MAX   = INIVAL_GRIDSEARCH_DPEAKMJD(2)
      DIFMJD_BIN   = INIVAL_GRIDSEARCH_DPEAKMJD(3)

c     D. Jones color grid search
      COLOR_INI  = INIVAL(IPAR_COLOR)
      COLOR_SAVE = INIVAL(IPAR_COLOR)
      COLOR_MIN   = INIVAL_GRIDSEARCH_COLOR(1)
      COLOR_MAX   = INIVAL_GRIDSEARCH_COLOR(2)
      COLOR_BIN   = INIVAL_GRIDSEARCH_COLOR(3)

      DO_PEAKMJD = (INISTP_PEAKMJD > 0.0 .and. DIFMJD_BIN > 0.0001)
      DO_COLOR   = (INISTP_COLOR   > 0.0 .and. COLOR_BIN  > 0.0001)

      IF ( .not. DO_COLOR ) THEN
        COLOR_MIN = COLOR_INI
        COLOR_MAX = COLOR_INI
        COLOR_BIN = 999.0   ! avoid infinite loop if no color bins
      ENDIF

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 4")

      if ( .not. DO_PEAKMJD ) GOTO 444

      CHI8MIN = CHI8INI
      COLOR   = COLOR_MIN

      DO 300 WHILE ( COLOR < COLOR_MAX+0.0001 )
        INIVAL(IPAR_COLOR) = COLOR
        DIFMJD = DIFMJD_MIN
      DO 400 WHILE ( DIFMJD < DIFMJD_MAX+0.001 )
        INIVAL(IPAR_PEAKMJD) = PEAKMJD_INI + DIFMJD

        CALL FCNSNLC(NFITPAR_MN,GRAD,CHI8,INIVAL,IFLAG,USRFUN)
        if ( CHI8 .LT. CHI8MIN ) then
            chi8min = chi8
            PEAKMJD_SAVE = INIVAL(IPAR_PEAKMJD)
            COLOR_SAVE = INIVAL(IPAR_COLOR)
        endif
        DIFMJD = DIFMJD + DIFMJD_BIN
400   CONTINUE
        COLOR = COLOR + COLOR_BIN
300   CONTINUE

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 5")

c load inital PEAK MJD and re-run FCNSNLC to update EP_FLUX_MODEL

      IF ( CHI8MIN < CHI8INI ) THEN
       ! save new initial values at min chi2 on very course grid
        INIVAL(IPAR_PEAKMJD) = PEAKMJD_SAVE
        INIVAL(IPAR_COLOR) = COLOR_SAVE
      ELSE
       ! restore original values
        INIVAL(IPAR_PEAKMJD) = PEAKMJD_INI
        PEAKMJD_SAVE         = PEAKMJD_INI
        INIVAL(IPAR_COLOR)   = COLOR_INI
        COLOR_SAVE           = COLOR_INI
      ENDIF

      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI8,INIVAL,IFLAG,USRFUN)

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 6")

c - - - - -
      if ( LPRINT ) then
         LCHAR  = INDEX(PARNAME_STORE(IPAR_PEAKMJD),' ') - 1
         LCHAR2 = INDEX(PARNAME_STORE(IPAR_COLOR),  ' ') - 1
         IF ( DO_COLOR ) THEN
           write(6,42)
     &         PARNAME_STORE(IPAR_PEAKMJD)(1:LCHAR),
     &         PARNAME_STORE(IPAR_COLOR)(1:LCHAR2),
     &         PEAKMJD_INI, COLOR_INI,
     &         INIVAL(IPAR_PEAKMJD), INIVAL(IPAR_COLOR), CHI8
         ELSE
           write(6,41) PARNAME_STORE(IPAR_PEAKMJD)(1:LCHAR),
     &               PEAKMJD_INI, INIVAL(IPAR_PEAKMJD), CHI8
         ENDIF

41       format(T10,'Adjust ',A,'=',F9.3, ' ==> ', F9.3,
     &             2x, '(CHI2=',F10.2,')'  )

42       format(T6,'Adjust ',A,'/',A, '=',
     &        F9.3,'/',F6.3, ' ==> ', F9.3,'/',F6.3,
     &        2x, '(CHI2=',F10.2,')'  )

      endif

444   CONTINUE

c -----------------------------------------------------
c Now check Data vs. Model;
c The data/model flux ratio-average will serve as
c an estimator for peakmag(data)-peakmag(model).

      RATIO_FLUX_AVG = 0.0
      NFILT          = 0
      DO 105 ifilt = 1, NFILTDEF_SURVEY
        ifilt_obs  = IFILTDEF_MAP_SURVEY(ifilt)
        if ( USE_FILT(ifilt_obs) ) then
          Rflux                 = DATA_MODEL_RATIO(ifilt)
          RATIO_FLUX(ifilt_obs) = Rflux
          RATIO_FLUX_AVG        = RATIO_FLUX_AVG + Rflux
          NFILT                 = NFILT + 1
        endif
105   CONTINUE

      IF ( NFILT .GT.0 ) THEN
         RATIO_FLUX_AVG = RATIO_FLUX_AVG / float(NFILT)
      ELSE
         RATIO_FLUX_AVG = 1.0
      ENDIF

      IPAR_ADJUST = 0

      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 .and.
     &     INISTP_X0 > 0.0 ) THEN

         IPAR_ADJUST         = IPAR_X0

         if ( OPT_SALT2FIT .EQ. 0 ) then   ! nominal SALT2 fit
           INIVAL(IPAR_ADJUST) = INIVAL(IPAR_ADJUST)
     &                         * RATIO_FLUX_AVG

         else if ( OPT_SALT2FIT .EQ. 1 ) then
           INIVAL(IPAR_ADJUST) = INIVAL(IPAR_ADJUST)
     &                         + LOG10(RATIO_FLUX_AVG)

         else if ( OPT_SALT2FIT .EQ. 2 ) then
           INIVAL(IPAR_ADJUST) = INIVAL(IPAR_ADJUST)
     &                         - 2.5*LOG10(RATIO_FLUX_AVG)
         endif

      ELSE IF ( INISTP_DLMAG .GT. 0.0 ) THEN
         IPAR_ADJUST         = IPAR_DLMAG
         INIVAL(IPAR_ADJUST) = INIVAL(IPAR_ADJUST)
     &                        -2.5*LOG10(RATIO_FLUX_AVG)
      ENDIF

c #########################################

      if ( LPRINT ) then

         NF = 0
         CFILT = ' '
         DO ifilt    = 1, NFILTDEF_SURVEY
           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
           if ( USE_FILT(ifilt_obs) ) then
             NF = NF + 1
             LCHAR = INDEX(CFILT,' ') - 1
             CFILT = CFILT(1:LCHAR)
     &             // FILTDEF_STRING(ifilt_obs:ifilt_obs)
             RTMP(NF) = RATIO_FLUX(ifilt_obs)
          endif
         ENDDO

         write(6,51) CFILT(1:NF) // ' Data/Model flux-ratio'
         DO IFILT = 1,  NF
           write(6,52) RTMP(IFILT)
         ENDDO
         print*,' '

         if ( IPAR_ADJUST .GT. 0 ) then
           CPAR = PARNAME_STORE(IPAR_ADJUST)
           LTMP = INDEX(CPAR,' ') - 1
           write(6,54)
     &        CPAR(1:LTMP)
     &       ,INIVAL_START(IPAR_ADJUST)
     &       ,INIVAL(IPAR_ADJUST)
        endif

51       format(T4, A, ' :', $ )
52       format(F7.3, $ )
54       format(T8,A,' = ', G10.3,' ==> ', G10.3 )


      ENDIF ! end of LDMP block

      if ( LTRACE ) CALL DMPTRACE("INSIDE FITINI_ADJUST: 8")


c -------------------------------------------
c check chi2 at end of adjustment

      CALL FCNSNLC(NFITPAR_MN,GRAD,CHI8END,INIVAL,IFLAG,USRFUN)

      if ( LPRINT ) then
        write(6,56) 'AFTER ', chi8end,  NEPOCH_ALL(0)
      endif

56    format(T4,'FCNSNLC(',A,' FITINI_ADJUST)    returns   CHI2=',
     &      F10.2,'/',I3)

c -----------------------------------------------
c if final chi2 is worse, then switch back to initial parameters
c and minimized PEAKMJD

      IF ( CHI8END .GT. CHI8INI ) THEN
        if ( STDOUT_UPDATE ) then
          print*,' '
          print*,'  WARNING: ADJUSTED CHI2 is WORSE => '
          print*,'           SWITCH BACK TO ORIGINAL INIVAL '
        endif

        DO ipar = 1, IPAR_MAX
          INIVAL(ipar) = INIVAL_START(ipar)
        ENDDO
        INIVAL(IPAR_PEAKMJD) = PEAKMJD_SAVE  ! save new PEAKMJD
      ENDIF

      CALL FLUSH(6)

      RETURN
      END  ! end FITINI_ADJUST

C ==========================
CDECK  ID>,  FITINI_LIST_FILE. 
      SUBROUTINE FITINI_LIST_FILE(iter)

C Created Apr 29 2022 by R.Kessler
c If &SNLCINP SNCID_LIST_FILE is set, check for previous SALT2 fit
c values to use as INIVAL when iter=1.
c If INISTP(ipar)=0 [fixed parameter value],
c apply previous SALT2 fit value for all iterations.

      IMPLICIT NONE

      INTEGER ITER ! (I) fit iteration


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER IPAR_LIST(20), NPAR, i, ipar
      INTEGER ABORT_FLAG, LENV
      LOGICAL USE_FITPAR_LIST_FILE
      REAL*8  DVAL
      CHARACTER cVAR*40
      LOGICAL LDMP, FIRST_ITER, LSET

      REAL*8   MATCH_CIDLIST_PARVAL
      EXTERNAL MATCH_CIDLIST_PARVAL

C ----------- BEGIN ----------

      USE_FITPAR_LIST_FILE = BTEST(OPT_SNCID_LIST,1)
      IF ( .NOT. USE_FITPAR_LIST_FILE ) RETURN

      FIRST_ITER = (ITER==1 .and. .not. LREPEAT_ITER)

c construct list of params to check in SNCID_LIST file

      NPAR = 0

      NPAR = NPAR + 1
      IPAR_LIST(NPAR) = IPAR_PEAKMJD
      NPAR = NPAR + 1
      IPAR_LIST(NPAR) = IPAR_X0
      NPAR = NPAR + 1
      IPAR_LIST(NPAR) = IPAR_SHAPE
      NPAR = NPAR + 1
      IPAR_LIST(NPAR) = IPAR_COLOR

      IF ( DOFIT_PHOTOZ ) THEN
        NPAR = NPAR + 1
        IPAR_LIST(NPAR) = IPAR_zPHOT
      ENDIF

      ABORT_FLAG = 0 ! do not abort on missing variable.

      LDMP = STDOUT_UPDATE

      DO 50 i = 1, NPAR
         IPAR = IPAR_LIST(i)
         LSET = (FIRST_ITER .or. INISTP(IPAR)==0.)
         IF (.not. LSET) GOTO 50
         LENV = INDEX(PARNAME_STORE(IPAR),' ') - 1
         cVAR = PARNAME_STORE(IPAR)(1:LENV) // char(0)
         if ( IPAR == IPAR_zPHOT ) cVAR = 'zHD' // char(0)

         DVAL =
     &     MATCH_CIDLIST_PARVAL(INDEX_CID_MATCH, cVAR, ABORT_FLAG,40)
         if ( DVAL > -999.0 ) THEN
             INIVAL(IPAR) = DVAL
             if ( LDMP ) then
               write(6,44) PARNAME_STORE(IPAR), DVAL, SNLC_CCID
 44            format(T8, 'INIVAL ', A8,' -> ', G12.5,
     &             ' from list file: CID=',A12)
             endif
         ENDIF
 50   CONTINUE

      CALL FLUSH(6)

      RETURN
      END  ! end FITINI_LIST_FILE

C =====================================
CDECK  ID>,  FITINI_TABLEVAR. 
      SUBROUTINE FITINI_TABLEVAR

c -----------------------------------------------
c define extra "PLOTVAR" variables to plot along
c with fit values. These are all plotted as a
c function of ISN.
c
c Jul 21, 2009: fix index bug inside LSIM if-block;
c               increment NPLOTPAR at end of bloc, instead of at start.
c
c Sep 2, 2010: check NPLOTPAR array bound before filter loop
c Feb 13,2012: check NFILTDEF_FITRESTMAG
c
c Sep 29, 2012: call CWNT_DUPLICATE_FILTER(i)  to check for duplicate
c               filter for case-insensitive ntuple.
c
c Jun 24 2013: always ignore FILTER_REPLACE filters for plotting.
c
c Mar 5 2020: ad NPTFIT_REJECT (due to DELCHI2)
c
c -----------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM.  Added Feb 2012 inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


      CHARACTER cfilt_obs*2, cfilt_rst*1, cfilt*1
      INTEGER   ipar, ifilt, ifilt_obs, ifilt_rst, i
      INTEGER   NTMP, NFADD, IFILTDEF
      LOGICAL   REPLACE, DOFIT

c function
      LOGICAL  DUPLICATE_FILTER
C -------------- BEGIN -------------

c Oct 27, 2011:
c get fixed number of filters to include in plots and ntuple,
c and create mapping between this fitted subset and
c the complete list of NFILTEDEF_SURVEY
c

      NFILTOBS_TABLE = 0
      SURVEY_FILTERS_TABLE = ' '

      DO 624 ifilt = 1, NFILTDEF_SURVEY

           ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)

           REPLACE  = (IFILTOBS_REPLACE(ifilt_obs) .NE. IFILT_OBS)
           IF ( REPLACE ) GOTO 624  ! always ignore a replaced filter

           DOFIT   = DOFIT_FILT(ifilt_obs)

           if ( DOFIT ) then
               NFILTOBS_TABLE = NFILTOBS_TABLE + 1
               IFILTOBS_MAP_TABLE(NFILTOBS_TABLE) = ifilt_obs
               IFILT_MAP_TABLE(NFILTOBS_TABLE)    = ifilt

               SURVEY_FILTERS_TABLE =
     &           SURVEY_FILTERS_TABLE(1:NFILTOBS_TABLE-1) //
     &           FILTDEF_STRING(IFILT_OBS:IFILT_OBS)
           endif
624   CONTINUE

c - - - - - - - - - - - - - - - - - - - - -
c check filter-REMAP option (Feb 2017)
      IF ( NFILT_REMAP_TABLE > 0 ) THEN
        NFILTOBS_TABLE       = NFILT_REMAP_TABLE
        SURVEY_FILTERS_TABLE = FILTLIST_REMAP_TABLE
        DO ifilt = 1, NFILT_REMAP_TABLE
           IFILTOBS_MAP_TABLE(ifilt) = IFILTLIST_REMAP_TABLE(ifilt)
        ENDDO
      ENDIF

c ----------------------
c define names of extra calculated parameters to plot;
c these parnames are used only in HFFITRES

      NPLOTPAR = IPAR_MAX

c make sure we don't exceed bound before filling arrays
      NTMP = NPLOTPAR + 7 * NFILTDEF_SURVEY
      if ( NTMP .GT. MXFITSTORE ) then
        write(c1err,662) 'Filter', NTMP
        write(c2err,663) MXFITSTORE
        CALL MADABORT ( "FITINI_TABLEVAR", c1err, c2err )
      endif


c add chi2 info for global fit.
      PARPTR_CHI2     =  NPLOTPAR  ! mark pointer-offset to global chi2 vars

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'NDOF'
      PAROPT_STORE(NPLOTPAR)  = OPT_PARSTORE_TEXTTABLE

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'NPTFIT_REJECT'  ! Mar 2020

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'FITCHI2'
      PAROPT_STORE(NPLOTPAR)  = OPT_PARSTORE_TEXTTABLE

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'PRIORCHI2'

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'SIGCHI2'   ! used when DOCHI2_SIGMA=T

      IF ( LSIM_SNANA ) THEN
        NPLOTPAR        =  NPLOTPAR + 1
        PARNAME_STORE(NPLOTPAR) = 'SIMCHI2'
      ENDIF

c --- now the fit-probs

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'FITPROB_NOMARG' ! includes prior, before marg

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'FITPROB'    ! includes prior, after marg
      PAROPT_STORE(NPLOTPAR)  = OPT_PARSTORE_TEXTTABLE

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'FITPROB_NOPRIOR'    ! excludes prior

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'RADIUS_POP'  ! Jan 2024
      PAROPT_STORE(NPLOTPAR)  = 1

c init everything, even for unused filters.

      DO 555 i = 1, NFILTOBS_TABLE  ! loop over observer-frame filters

        ifilt_obs  = IFILTOBS_MAP_TABLE(i)
        ifilt      = IFILT_MAP_TABLE(i)
        cfilt_obs  = FILTDEF_STRING(ifilt_obs:ifilt_obs)

c check for duplicate 'HBOOK' filters such as g,G or r,R ...
c perfectly allowed in snana, but ntuples cannot distinguish
c since they are case-insensitive.
        IF ( DUPLICATE_FILTER(i,SURVEY_FILTERS_TABLE) ) THEN
           cfilt_obs = cfilt_obs(1:1) // '2'  ! for ntuple distinction
        ENDIF

        NFADD = 0
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'm0obs_' // cfilt_obs

        NFADD = NFADD + 1
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'em0obs_' // cfilt_obs

        if ( NFILTOBS_TABLE .GT. 20 ) GOTO 555

        NFADD = NFADD + 1
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'PEAKFLUX_' // cfilt_obs

        NFADD = NFADD + 1
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'EPEAKFLUX_' // cfilt_obs

        NFADD = NFADD + 1
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'Nepoch_' // cfilt_obs

        NFADD = NFADD + 1
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'chi2_' // cfilt_obs

        NFADD = NFADD + 1
        ipar = NPLOTPAR + i + NFADD*NFILTOBS_TABLE
        PARNAME_STORE(ipar) = 'FITPROB_' // cfilt_obs

555   CONTINUE

      NPLOTPAR = NPLOTPAR + (NFADD+1) * NFILTOBS_TABLE


c plot peakMags in rest-frame.
c The number of rest-frame filters can be different
c than the number of observer-frame filters,
c so do NOT put this part into the 555 loop above.

      IF ( LREST_FITMODEL ) THEN
        DO ifilt     = 1, NFILTDEF_REST
         ifilt_rst = IFILTDEF_MAP_REST(ifilt)
         cfilt_rst = FILTDEF_STRING(ifilt_rst:ifilt_rst)
         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'm0rst_' // cfilt_rst

c pointer to assoc NPLOTVAR with ifilt-rest
         PARPTR_IFILT_REST(ifilt_rst) = NPLOTPAR
        ENDDO
      ENDIF

c Feb 2012: Optional FITRESTMAGs
      PARPTR_FITRESTMAG  =  NPLOTPAR  ! mark pointer-offset
      DO ifilt           = 1, NFILTDEF_FITRESTMAG
         IFILTDEF        = IFILTDEF_FITRESTMAG(ifilt)
         cfilt           = FILTDEF_STRING(ifiltdef:ifiltdef)

         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'M0_' // cfilt
         PAROPT_STORE(ipar)  = OPT_PARSTORE_TEXTTABLE

         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'ERRM0_' // cfilt
         PAROPT_STORE(ipar)  = OPT_PARSTORE_TEXTTABLE
      ENDDO

c Mar 2013: optional FITMAGDIF
      IF ( FILTER_FITMAGDIF .NE. '' ) THEN
         cfilt = FILTER_FITMAGDIF

         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'MAGDIF_' // cfilt
         PAROPT_STORE(ipar)  = OPT_PARSTORE_TEXTTABLE

         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'ERRMAGDIF_' // cfilt
         PAROPT_STORE(ipar)  = OPT_PARSTORE_TEXTTABLE

         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'MAGDIF_FITPROB_' // cfilt

         NPLOTPAR        = NPLOTPAR + 1
         ipar            = NPLOTPAR
         PARNAME_STORE(ipar) = 'MAGDIF_FITPROB2_' // cfilt

      ENDIF

c April 2013: optional peak-mag(s) in other observer-frame filters
c             e.g.: FILTLIST_FIT = 'ugriz+BV' -> include B&V peak mags

c ---

      NPLOTPAR            =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'delZ'

      NPLOTPAR            =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'delmu'

c Dec 5, 2006: extra Z plots for PHOTOZ fits.

      NPLOTPAR        =  NPLOTPAR + 1
      PARNAME_STORE(NPLOTPAR) = 'delZph'

      if ( NPLOTPAR .GT. MXFITSTORE ) then
        write(c1err,662) 'FINAL', NPLOTPAR
662     format(A, ' NPLOTPAR = ', I3 )
        write(c2err,663) MXFITSTORE
663     format('Exceeds MXFITSTORE = ', I4 )
        CALL MADABORT ( "FITINI_TABLEVAR", c1err, c2err )
      endif

      RETURN
      END      ! end FITINI_TABLEVAR

C =====================================
CDECK  ID>,  FINI_PRKCOR. 
      SUBROUTINE FITINI_PRKCOR()
      IMPLICIT NONE
c
c print info about K corrections
c


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c local var

      CHARACTER cfilt*1
      INTEGER   ifilt_rest1, ifilt_rest2, ifilt_obs, ifilt
      REAL Z, LAMDIF_MIN

c function
      INTEGER NEAREST_IFILTDEF_WRAPPER

C -------------- BEGIN -------------


      z = REDSHIFT_FIT
      print*,' '
      DO 700 ifilt = 1, NFILTDEF_SURVEY  ! loop over observed filters

        ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
        if ( .NOT. USE_FILT(ifilt_obs) ) goto 700

        ifilt_rest1 =
     &    NEAREST_IFILTDEF_WRAPPER( OPT_FILTOBS, ifilt_obs,
     &             1,Z, LAMDIF_MIN)
        ifilt_rest2 =
     &    NEAREST_IFILTDEF_WRAPPER( OPT_FILTOBS, ifilt_obs,
     &             2,Z, LAMDIF_MIN)

        write(6,701)
     &    SNLC_CCID(1:ISNLC_LENCCID)
     &   ,filtdef_string(ifilt_obs:ifilt_obs)
     &   ,filtdef_string(ifilt_rest1:ifilt_rest1)
     &   ,filtdef_string(ifilt_obs:ifilt_obs)
     &   ,filtdef_string(ifilt_rest1:ifilt_rest1)
     &   ,filtdef_string(ifilt_rest2:ifilt_rest2)
     &   ,OPT_FILTOBS

701      FORMAT(T5,'CID=',A, ' : ',
     &             A,'-band KCOR = K_', A,A,
     &         ' ; AVwarp from ', A,'-', A, 3x,'(OPT=',I2,')' )

700   CONTINUE

      RETURN
      END   ! FITINI_PRKCOR


C =====================================
CDECK  ID>,  FINI_COV. 
      SUBROUTINE FITINI_COV(MSKOPT, ITER, FITPAR, IERR)

c ---------------------------
c init FITCOV arrays used in FCNSNLC and also used
c to get covariance matrix.
c MSKOPT: bit 1 => print  info to stdout
c ITER = 1, 2, ... = fit iteration.
c
c
c Feb 2020: add OPT_COVAR_MWXT==2 option to include only DIAG part.
c May 2021: pass param lists to gencovar_SALT2
c
c ----------------------------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER MSKOPT     ! (I) bit-mask of options
      INTEGER ITER       ! (I) fit iteration
      REAL*8  FITPAR(MXFITPAR) ! (I) fit parameters
      INTEGER IERR       ! (O) 0 => ok

c local var

      INTEGER
     &   ifilt, ifilt_obs, ifilt_rest, ifilt1, ifilt2, ISTAT
     &  ,irow, icol, J1, N, ep, ep_row, ep_col
     &  ,IR(MXFIT_DATA), IFILT_COV(MXFIT_DATA)
     &  ,IFAIL, JFAIL, IFROW, IFCOL, LCCID, NONZERO
     &  ,FIRSTITER_USECOV

      REAL*8
     &   COVTMP, RHO, Z, MWEBV, RHO_TMP, DET, ARG
     &  ,TOBS(MXFIT_DATA)
     &  ,TREST(MXFIT_DATA)
     &  ,COVMAG_ERR(MXFIT_DATA)
     &  ,SQMAGERR, SQFLUXERR, FF
     &  ,R1, R2, F1, F2, ERR1, ERR2, FUDGE_SQERR, ERRSCALE
     &  ,COV_MWXT, COV_MODEL, COV_DATA, COV_TMP
     &  ,PARLIST_SN(10), PARLIST_HOST(10)

      LOGICAL
     &  LPRINT, USE_DIAG_ONLY, LTMP, LDIAG, FIRST_ITER, CHECK_COV
     & ,LMWXT

      character BANNER*60, ccid*(MXCHAR_CCID), FNAM*12

c functions
      INTEGER
     &   gencovar_mlcs2k2
     &  ,gencovar_SALT2

      LOGICAL FIRST_ITERATION
      REAL*8 RHOFUDGE_MODEL, COVFUDGE_DATA

      EXTERNAL INVERTMATRIX

C ------------------- BEGIN ---------------

      IERR = 0   ! init output flag to OK

      FIRST_ITER = FIRST_ITERATION(ITER)

      LPRINT = BTEST(MSKOPT,0) .and. STDOUT_UPDATE
      FNAM   = 'FITINI_COV'
      CCID   = SNLC_CCID
      LCCID  = ISNLC_LENCCID

      IF ( LPRINT ) THEN
        write(BANNER,19) CCID(1:LCCID), iter
19      format('FITINI_COV: init fit arrays for CID=',A,' ITER=',I1)
        CALL PRBANNER(BANNER)
      ENDIF

c init

c -------------------------------
c  Fill R4EP_XXX and I4EP_XXX arrays.

      CALL LOAD_EPALL(ITER, FITPAR(IPAR_PEAKMJD) )

      NFITDATA_TOTAL = NFITDATA + NFITDATA_REJECT

c -------------------------------
c load some local arrays.

        DO N = 1, NFITDATA_TOTAL
           ep = EPLIST_FIT(N)

           ifilt_obs  = I4EP_ALL(ep,IEP_IFILT_OBS)
           ifilt_rest = I4EP_ALL(ep,IEP_IFILT_REST1)

           IF ( LREST_FITMODEL ) THEN
              IFILT_COV(N) = IFILTDEF_INVMAP_REST( IFILT_REST ) - 1
           ELSE
              IFILT_COV(N) = IFILT_OBS
           ENDIF

           TREST(N)    = dble( R4EP_ALL(ep,JEP_TREST) )
           TOBS(N)     = dble( R4EP_ALL(ep,JEP_TOBS)  )

        ENDDO

c -------------------------------------------------
c set flag to use diagonal elements only if
c OPT_COVAR_FLUX <= 0 or if this is the 1st iteration

      CHECK_COV = (.NOT. FIRST_ITER)
      if ( OPT_SALT2FIT.EQ.4 ) CHECK_COV = ( ITER .EQ. 3 ) ! mimic Guy-code

      USE_FITCOV = .FALSE.
      IF ( CHECK_COV ) THEN
        if ( OPT_COVAR_FLUX     > 0    ) USE_FITCOV = .TRUE. ! model cov
        if ( OPT_COVAR_MWXTERR  > 0    ) USE_FITCOV = .TRUE. ! MWEBV cov
        if ( FUDGE_MAG_COVERR .NE. ' ' ) USE_FITCOV = .TRUE. ! data cov
      ENDIF
      USE_DIAG_ONLY = .NOT. USE_FITCOV

      IF ( LPRINT ) THEN
        write(6,21) NFITDATA,          'ACCEPTED'
        write(6,21) NFITDATA_REJECT,   'REJECTED'
21      format(T8,I4, 2x, 'Filter-epochs ', A,' for fit.' )

        if ( USE_DIAG_ONLY ) then
           CALL  PRINT_ITERINFO(CCID,ITER,
     &           'Use DIAGONAL Covariance elements only.')
        else
           write(BANNER,5551) NFITDATA, NFITDATA
5551       format('Use full ',I4,' x ',I4,' Covariance matrix.')
           CALL  PRINT_ITERINFO(CCID,ITER, BANNER)
        endif

        IF ( .NOT. FIRST_ITER  ) THEN
          if ( OPT_COVAR_FLUX .GT. 0 ) THEN
             CALL  PRINT_ITERINFO(CCID,ITER,
     &             'Add covariance from fit-model')
          endif
          if ( OPT_COVAR_MWXTERR > 0 ) then
             CALL  PRINT_ITERINFO(CCID,ITER,
     &             'Add covariance from Galactic extinction')
          endif

          if ( FUDGE_MAG_COVERR .NE. ' ' ) then
             CALL  PRINT_ITERINFO(CCID,ITER,
     &             'Add covariance fudges from data.')
          endif
        ENDIF


      ENDIF

c 670   format(T8,'Use ',I3,' x ', I3,' Covariance computed ', A)

c --------------------------------------
      IF ( NFITDATA .LE. 0 ) THEN
        print*,' '
        print*,' FITINI_COV ERROR for CID = ', CCID(1:LCCID)
        print*,'   Nothing to fit ??? [NFITDATA=',NFITDATA,']'
        print*,'   Either remove this SN, or fix it. '
        print*,' '
        call flush(6)
c .xyz
        if ( ABORT_ON_NOEPOCHS ) then
           C1ERR = 'Nothing to fit for CID = ' // CCID(1:LCCID)
           C2ERR = 'To avoid abort, set   ABORT_ON_NOEPOCHS=F '
           CALL MADABORT(FNAM, C1ERR, C2ERR)
        else
           IERR = ERRFLAG_FITPREP_NOEPOCHS
           RETURN
        endif

      ENDIF


      IF ( NFITDATA .LT. int(CUTWIN_NEPOCH(1)) ) then
        print*,'   FITINI_COV WARNING for CID = ', CCID(1:LCCID),
     &      ' :   too few epochs to fit. '
        IERR = ERRFLAG_FITPREP_NEPOCH
        RETURN
      ENDIF

c =====================================================
c =====================================================
c =====================================================

c alway init covariance matrix to zero

      DO irow = 1, NFITDATA
      DO icol = 1, NFITDATA
         COVMAT2(irow,icol) = 0.0
         J1 = icol + (irow-1)*NFITDATA     ! 1-dim index for COVMAT1
         COVMAT1(J1) = 0.0
      ENDDO
      ENDDO

c ---------------------------------------------
      IF ( USE_DIAG_ONLY  ) RETURN
c ---------------------------------------------


c ----------------------------------------------------
c get COVMAT1 covariance matrix on 2nd iteration
c This linear array is converted below into a 2-dim array.
c This is the model-covariance only.

      IF ( OPT_COVAR_FLUX .GT. 0 ) THEN
        IF ( FITMODEL_INDEX .EQ. MODEL_MLCS2k2 ) THEN
          ISTAT = gencovar_mlcs2k2(NFITDATA, IFILT_COV, TREST,
     &               COVMAT1 )  ! ==> returned

        ELSE if ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN

           Z        = REDSHIFT_FIT
           MWEBV    = SNLC_MWEBV
           PARLIST_SN(1) = FITPAR(IPAR_x0   )
           PARLIST_SN(2) = FITPAR(IPAR_SHAPE)
           PARLIST_SN(3) = FITPAR(IPAR_COLOR)
           PARLIST_HOST(1) = 0.0  ! cannot fit RV
           PARLIST_HOST(2) = 0.0  ! cannot fit AV
           PARLIST_HOST(3) = -9.0 ! cannot fit logMass

           ISTAT = gencovar_SALT2(NFITDATA, IFILT_COV, TOBS, Z
     &             ,PARLIST_SN, PARLIST_HOST  ! (I)
     &             ,MWEBV                     ! (I) MW extinction
     &             ,COVMAT1 )         ! <== returned array, MAGERR^2

        ELSE
          C1ERR = 'No covariance model for FITMODEL='
     &             // FITMODEL_VERSION(1:20)
          C2ERR = 'Set OPT_COVAR_FLUX = 0 for this model'
          CALL MADABORT('FITINI_COV', C1ERR, C2ERR)
        ENDIF
      ENDIF

c print rho-fudge formula by calling with args = 0
      LTMP = OPT_COVAR_FLUX .LE. 1  ! print comment for these OPT_COVAR_FLUX
      IF ( LTMP ) THEN
        RHO_TMP = RHOFUDGE_MODEL(0, 0, DBLE(0.0) )
      ENDIF

c -------------------------------------------------------------
c fill the 2d matrix, COVMAT2, and store diagonal errors.

       DO 301 irow = 1, NFITDATA
       DO 302 icol = 1, NFITDATA

         J1 = icol + (irow-1)*NFITDATA     ! 1-dim index for COVMAT1

c transfer to 2D array
         COVMAT2(irow,icol) = COVMAT1(J1)

c store diag errors in mag space
         if ( irow .EQ. icol ) then
            COVMAG_ERR(irow)  = dsqrt ( COVMAT1(J1) )
         endif

302    CONTINUE
301    CONTINUE

cc       CALL DMP_COVAR(iter)  ! for DEBUG only

       FUDGE_SQERR = FUDGE_MODELERR_SCALE**2

c now convert COVMAT2 model-magerr^2 to  model-fluxerr^2,
c and add data errors. Note that COVMAT2 changes here.

c COVMAT1/COVMAT2 is the model-magerr covariance.
c Below convert to FLUXERR covariance and add the following
c  - XTMW covariance
c  - model-err cov
c  - data error covariance
c
c Also fill the 2d matrix, COVMAT2

       DO 311 irow = 1, NFITDATA
       DO 312 icol = 1, NFITDATA

          ep_row = EPLIST_FIT(irow)
          ep_col = EPLIST_FIT(icol)

          COV_MODEL = 0.0
          COV_MWXT  = 0.0
          COV_DATA  = 0.0

          LDIAG = (IROW .EQ. ICOL)

c start with model covariance
          IF ( OPT_COVAR_FLUX .GT. 0 ) THEN
             SQMAGERR = COVMAG_ERR(irow) * COVMAG_ERR(icol)
             RHO_TMP  = COVMAT2(irow,icol) / SQMAGERR ! reduced cov.

c check user-option to  'fudge' rho
             RHO = RHOFUDGE_MODEL ( irow, icol, RHO_TMP )

c get the model covariance
             R1   = 1.0 - 10.0**(-0.4*COVMAG_ERR(irow)) ! frac err, sigF/F
             R2   = 1.0 - 10.0**(-0.4*COVMAG_ERR(icol)) ! frac err

             ERR1 = R1 * R4EP_ALL(ep_row,JEP_MODELFLUX) ! flux error
             ERR2 = R2 * R4EP_ALL(ep_col,JEP_MODELFLUX) ! flux error
             COV_MODEL =  RHO * ERR1 * ERR2 * FUDGE_SQERR

          ELSE IF ( LDIAG ) THEN
c note that FUDGE_MODELERR_SCALE has already been
c applied to R4EP_MODELFLUX_ERR
             ERR1 = R4EP_ALL(ep_row,JEP_MODELFLUX_ERR)
             COV_MODEL = ERR1 * ERR1
         ENDIF

c check option to turn off model error.
         IF ( FUDGE_MAGERR_MODEL .EQ. 0.0 ) COV_MODEL = 0.0

c check for XTMW covariance
         LMWXT = (OPT_COVAR_MWXTERR == 1) .or.        ! full COV
     &           (OPT_COVAR_MWXTERR == 2 .and. LDIAG) ! diag only
         IF ( LMWXT ) THEN
            ERR1 = R4EP_ALL(ep_row,JEP_MWXT_FLUXERR)
            ERR2 = R4EP_ALL(ep_col,JEP_MWXT_FLUXERR)
            COV_MWXT = ERR1 * ERR2
         ENDIF

c Now add diagonal error from data and user fudges.
         if ( LDIAG ) then
            COV_DATA  = R4EP_ALL(ep_row,JEP_DATAFLUX_ERR)**2
     &                + R4EP_ALL(ep_row,JEP_FUDGEFLUX_ERR)**2
         endif

c add cov fudge-error for data (Feb 2015)
         COV_DATA = COV_DATA + COVFUDGE_DATA( irow, icol )

c redefine COVMAT2 in fluxerr space
         COVMAT2(irow,icol) = COV_MODEL + COV_MWXT + COV_DATA

312    CONTINUE
311    CONTINUE

cc       CALL DMP_COVAR(iter)  ! for DEBUG only DDDDDDDD

c invert COVMAT2 matrix.

       CALL INVERTMATRIX( MXFIT_DATA, NFITDATA, COVMAT2)

c !!! Now COVMAT2 is the inverted COV matrix !!!

c check for min value of inverted matrix

      COVMAT_MIN = +9999.
      COVMAT_MAX = -9999.
      NONZERO = 0

      DO irow = 1, NFITDATA
      DO icol = 1, NFITDATA
         COVTMP = COVMAT2(irow,icol)
         COVMAT_MIN = MIN ( COVMAT_MIN, COVTMP )
         COVMAT_MAX = MAX ( COVMAT_MAX, COVTMP )
         if ( COVTMP .NE. 0.0 ) NONZERO = NONZERO + 1
      ENDDO
      ENDDO


      if ( LPRINT ) then
        write(BANNER,5555) NONZERO
5555    format('Inverted COVMAT with ',I6,' non-zero elements')
        CALL  PRINT_ITERINFO(CCID,ITER, BANNER(1:52) )
      endif

      CALL FLUSH(6)

      RETURN
      END      ! end of FITINI_COV

C =====================================
CDECK  ID>,  LOAD_EPALL. 
      SUBROUTINE LOAD_EPALL(ITER,PKMJD8)

c Created Sep 28, 2012
c
c Fill R4EP_ and I4EP_ arrays so that first NFITDATA elements
c are the ones to fit; the next NFITDATA_REJECT elements
c are rejected epochs. This sorting is done so that FCNSLNC
c can efficiently compute chi2,  and still be able to record
c rejected epochs [when LAST=T] for plotting.
c When IREJ=0, store epochs to fit;
c when IREJ=1, tack on rejected epochs.
c
c Feb 26 2015: load CHI2FLUX_SIM for simulation (LSIM_SNANA=T).
c
c -------------------------

      IMPLICIT NONE

      INTEGER ITER  ! (I) fit iteration
      REAL*8  PKMJD8

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &   IFILT, IFILT_OBS, IREJ, IMJD, ep, EPMIN, EPMAX
     &  ,N, OPT, IF1, IF2, ifit, ivar, REJECT, REJECT2

      INTEGER ITER_DMP / -1 /
      REAL
     &   Z, Z1, TREST, MAXFRAC, LAMDIF_MIN, LAMREST
     &  ,FLUX_DATA, FLUXERR_STAT, FLUXERR_DATA, FLUX_SIM
     &  ,FLUX_MODEL, FLUXERR_MODEL, FLUXERR_TOT
     &  ,ERR_TRUE, ERR_CALC, ARG, TOBS, ERR_TMP, ZP
     &  ,SQDIF, SQERR

      REAL*8 FTMP8, MAGERR8, MJD8

      LOGICAL LTMP, LREJECT, LREJECT2

      character cfilt*1

c functions
      INTEGER NEAREST_IFILTDEF_WRAPPER
      LOGICAL MJDSELECT
      REAL*4 GET_FUDGE_FITERR_MAXFRAC

C ----------------- BEGIN ----------------

      N = 0
      NFITDATA        = 0
      NFITDATA_REJECT = 0

      DO ifilt = 0, MXFILT_OBS
         NEPOCH_ALL(ifilt)    = 0
         NEPOCH_FIT(ifilt)    = 0
         NEPOCH_REJECT(ifilt) = 0
      ENDDO
      NEPOCH_REJECT2 = 0

      Z = REDSHIFT_FIT
      Z1 = 1. + z

      ZP = SNGL(ZEROPOINT_FLUXCAL_DEFAULT)

c -------------------------------
c save previous R4ALL values in R4_LAST array in case
c previous iteration values are needed; e.g. FCNCHI2_SIGMA

      IF ( ITER > 1 ) THEN
         do ep = 1, MXFIT_DATA
            do ivar = 1, MXVAR_R4
               R4EP_LAST(ep,ivar) = R4EP_ALL(ep,ivar)
            enddo
         enddo
      ENDIF

c ---------------------------------

      DO 200 IREJ      = 0, 1  ! 0=keep, 1=reject

      DO 101 IMJD      = 1, ISNLC_NEWMJD_STORE

        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,IMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,IMJD)

      DO 102 ep = EPMIN, EPMAX

         MJD8   = SNLC8_MJD(ep)
         IF ( PKMJD8 .GT. 20000.0 ) then
           TOBS  = SNGL(MJD8 - PKMJD8)
         ELSE
           TOBS  = SNGL(MJD8 - (PKMJD8+MJDOFF) )
         ENDIF
         TREST   = TOBS/z1

         IFILT_OBS = ISNLC_IFILT_OBS(ep)
         cfilt     = filtdef_string(ifilt_obs:ifilt_obs)

         lamrest = FILTOBS_LAMAVG(ifilt_obs) / Z1

         if (  .NOT. USE_FILT(ifilt_obs)   ) goto 102

c find sparse index 'ifilt' that corresponds to IFILT_OBS
         ifilt = IFILTDEF_INVMAP_SURVEY(ifilt_obs)

         if ( ifilt .LE. 0 ) then
             write(c1err,660) ifilt_obs, cfilt
660          format('Could not find sparse index for IFILT_OBS= '
     &           ,I3, ' (',A,')'  )
             write(c2err,661) NFILTDEF_SURVEY, IFILTDEF_MAP_SURVEY
661          format('NFILTDEF_SURVEY=',I2,'  IFILTDEF_MAP_SURVEY=',10I3)
             CALL MADABORT("FITINI_COV", c1err, c2err )
         endif

         FLUX_DATA     = SNLC_FLUXCAL(ep)
         FLUXERR_STAT  = SNLC_FLUXCAL_ERRTOT(ep)
         FLUXERR_DATA  = SNLC_FLUXCAL_ERRTOT(ep)

c immediately skip epochs that fail cuts, or epochs whose
c flux-error is negative

        IF ( .not. MJDSELECT(imjd,0) ) GOTO 101

c check if this epoch is rejected
        REJECT   = I4EP_ALL(ep,IEP_REJECT)
        REJECT2  = I4EP_ALL(ep,IEP_REJECT2)

        LREJECT  = (iter > 1  .and. REJECT  > 0)
        LREJECT2 = (iter > 1  .and. REJECT2 > 0)

c count rejected epochs within TREST window
        IF ( LREJECT2 .and. IREJ .EQ. 1 ) then
           NEPOCH_REJECT2 = NEPOCH_REJECT2 + 1
        ENDIF


        IF ( LREJECT .and. IREJ .EQ. 1 ) then
c count all rejected epochs
           NEPOCH_REJECT(ifilt) = NEPOCH_REJECT(ifilt) + 1
           NEPOCH_REJECT(0)     = NEPOCH_REJECT(0)     + 1
           NFITDATA_REJECT      = NFITDATA_REJECT + 1

        ELSE IF ( .NOT. LREJECT .and. IREJ .EQ. 0 ) THEN
c count epochs used for fitting
           NEPOCH_FIT(ifilt)    = NEPOCH_FIT(ifilt) + 1
           NEPOCH_FIT(0)        = NEPOCH_FIT(0)     + 1
           NFITDATA             = NFITDATA + 1
        ELSE
           GOTO 102
        ENDIF

c increment number of epochs (fit + rejected)

        NEPOCH_ALL(ifilt) = NEPOCH_ALL(ifilt) + 1
        NEPOCH_ALL(0)     = NEPOCH_ALL(0)     + 1

        N = N + 1

        IF ( N > MXFIT_DATA ) GOTO 102

        EPLIST_FIT(N) = ep  ! allows FCN to quickly find useful epochs

        if ( ITER .EQ. ITER_DMP ) then
          write(6,454) N, ep, cfilt, MJD8
     &      ,MJD8 - SNLC_SEARCH_PEAKMJD, flux_data, fluxerr_data
454       format(I3,1x,'ep=',I3, 2x,A,2x,'MJD=',F7.2,2x,
     &        'Trest=',F6.2, 3x, 'Flux=',F6.1,'+-',F6.1 )
        endif

c get local flux and error from model (non-zero only if ITER > 1 )
        flux_model    = R4EP_ALL(ep,JEP_MODELFLUX)
        fluxerr_model = R4EP_ALL(ep,JEP_MODELFLUX_ERR)
        fluxerr_tot   = R4EP_ALL(ep,JEP_FLUX_ERRTOT)

c load FITCOV arrays
        I4EP_ALL(ep,IEP_IFILT)       = IFILT
        I4EP_ALL(ep,IEP_IFILT_OBS)   = IFILT_OBS
        I4EP_ALL(ep,IEP_IMJD)        = IMJD
        I4EP_ALL(ep,IEP_CCDNUM)      = ISNLC_CCDNUM(ep)
        I4EP_ALL(ep,IEP_IMGNUM)      = ISNLC_IMGNUM(ep)
        BANDEP_ALL(ep) = FILTDEF_STRING(IFILT_OBS:IFILT_OBS)

c Get nearest and 2nd nearest rest filter
c Also subtract index offsets

        IF ( LREST_FITMODEL ) THEN
          OPT = OPT_FILTOBS

          IF1 = NEAREST_IFILTDEF_WRAPPER(OPT,ifilt_obs,1,Z,LAMDIF_MIN)
          IF2 = NEAREST_IFILTDEF_WRAPPER(OPT,ifilt_obs,2,Z,LAMDIF_MIN)

          I4EP_ALL(ep,IEP_IFILT_REST1) = IF1
          I4EP_ALL(ep,IEP_IFILT_REST2) = IF2

          ARG   = 0.4*(ZP - SIM_EPMAGREST(ep))
          R4EP_ALL(ep,JEP_SIM_FLUXREST) = 10.0**(ARG)
          R4EP_ALL(ep,JEP_SIM_MAGREST) = SIM_EPMAGREST(ep)

        ENDIF

         R4EP_ALL(ep,JEP_SIM_FLUXCAL) = 0.0
         IF ( LSIM_MAGOBS .or. LSIM_SNANA ) THEN
            ARG   = 0.4*(ZP - SIM_EPMAGOBS(ep))
            FLUX_SIM = 10.0**(ARG)
            SQDIF    = (FLUX_SIM - FLUX_DATA)**2
            SQERR    = FLUXERR_DATA*FLUXERR_DATA

cc          print*,' xxxx ', ep, FLUX_SIM
            R4EP_ALL(ep,JEP_SIM_FLUXCAL) = FLUX_SIM
            IF ( FLUXERR_DATA > 0 ) THEN
               R4EP_ALL(ep,JEP_SIM_DELCHI2) = SQDIF/SQERR
            ELSE
               R4EP_ALL(ep,JEP_SIM_DELCHI2) = -9.0
            ENDIF
         ENDIF

        R8EP_MJD(N)           = MJD8

        R4EP_ALL(ep,JEP_MJD)           = SNGL(MJD8)
        R4EP_ALL(ep,JEP_DATAFLUX)      = FLUX_DATA
        R4EP_ALL(ep,JEP_DATAFLUX_ERR)  =
     &           FLUXERR_DATA * FUDGE_DATAERR_SCALE
        R4EP_ALL(ep,JEP_MODELFLUX)      = FLUX_MODEL
        R4EP_ALL(ep,JEP_MODELFLUX_ERR)  =
     &           FLUXERR_MODEL * FUDGE_MODELERR_SCALE
        R4EP_ALL(ep,JEP_FLUX_ERRTOT)    = FLUXERR_TOT
        R4EP_ALL(ep,JEP_TOBS)           = TOBS
        R4EP_ALL(ep,JEP_TREST)          = TREST

c check for epochs to add fudged errors so that these
c points are ignored in the fit, but are included in
c all plots.

        MAXFRAC =
     &     GET_FUDGE_FITERR_MAXFRAC(ITER,ifilt_obs,TREST,LAMREST)

        ERR_TMP = MAXFRAC * SNLC_FLUXCALMAX(ifilt)
        R4EP_ALL(ep,JEP_FUDGEFLUX_ERR)  = ERR_TMP
        R4EP_ALL(ep,JEP_FUDGE_MAXFRAC)  = MAXFRAC

c set error on MilkyWay Galactic extinction
         MAGERR8 = SNLC_MWXT_MAGERR(ifilt)
         FTMP8   = 1.0 - 10**(-0.4*MAGERR8)
         R4EP_ALL(ep,JEP_MWXT_MAGERR)  =  SNGL(MAGERR8)
         R4EP_ALL(ep,JEP_MWXT_FLUXERR) =  SNGL(FTMP8) * FLUX_MODEL

         R4EP_ALL(ep,JEP_LAMREST)     = LAMREST
         R4EP_ALL(ep,JEP_PSF)         = SNLC_PSF_SIG1(ep)
         R4EP_ALL(ep,JEP_NEA)         = SNLC_PSF_NEA(ep)
         R4EP_ALL(ep,JEP_SKYSIG)      = SNLC_SKYSIG(ep)
         R4EP_ALL(ep,JEP_SKYSIG_T)    = SNLC_SKYSIG_T(ep)
         R4EP_ALL(ep,JEP_ZP)          = SNLC_ZEROPT(ep)
         R4EP_ALL(ep,JEP_ZPERR)       = SNLC_ZEROPT_ERR(ep)
         R4EP_ALL(ep,JEP_GAIN)        = SNLC_GAIN(ep)
         R4EP_ALL(ep,JEP_XPIX)        = SNLC_XPIX(ep)
         R4EP_ALL(ep,JEP_YPIX)        = SNLC_YPIX(ep)
         R4EP_ALL(ep,JEP_AREAFRAC)    = SNLC_AREAFRAC(ep)
         R4EP_ALL(ep,JEP_SKYFLUXCAL)  = SNLC_SKYFLUXCAL(ep)
         R4EP_ALL(ep,JEP_SBFLUXCAL)   = SNHOST_SBFLUXCAL(ifilt)
         R4EP_ALL(ep,JEP_PHOTPROB)    = SNLC_PHOTPROB(ep)

         ERR_TRUE  = SNLC_FLUXCAL_ERRTOT(ep)
         ERR_CALC  = SNLC_FLUXCAL_ERRCALC(ep)
         ERR_TMP   = SNLC_FLUXCAL_ERRTEST(ep)

         R4EP_ALL(ep,JEP_ERRTEST) = ERR_TMP
         R4EP_ALL(ep,JEP_ERRCALC) = ERR_CALC

102   CONTINUE   ! end of EPMIN,EPMAX loop
101   CONTINUE   ! end of IMJD loop
200   CONTINUE   ! end of IREJ loop

c - - - - - -
      IF ( N > MXFIT_DATA ) THEN
           write(c1err,670) N, MXFIT_DATA, ITER,
     &           SNLC_CCID(1:ISNLC_LENCCID)
 670       format('NFIT_DATA=',I4, '  exceeds MXFIT_DATA=',I4, 3x,
     &          'for ITER=', I1, 2x,'CID=',A )
           c2err = 'Check param MXFIT_DATA'
           CALL MADABORT("LOAD_EPALL", c1err, c2err )
        ENDIF

      RETURN
      END      ! end of LOAD_EPALL

C ==========================================
CDECK  ID>,  LDEPFIT. 
      SUBROUTINE LOAD_EPFIT()

c Creatd Jan 25 2014
c Transfer R4EP_ALL -> sparse R4EP_FIT
c Transfer I4EP_ALL -> sparse I4EP_FIT

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER ifit, ivar, ep

C ------------- BEGIN ----------

c load sparse _FIT arrays

      DO 400 ifit = 1, NFITDATA + NFITDATA_REJECT
         ep = EPLIST_FIT(ifit)

         DO ivar = 1, MXVAR_R4
            R4EP_FIT(ifit,ivar) = R4EP_ALL(ep,ivar)
         ENDDO

         DO ivar = 1, MXVAR_I4
            I4EP_FIT(ifit,ivar) = I4EP_ALL(ep,ivar)
         ENDDO

         BANDEP_FIT(ifit) = BANDEP_ALL(ep)  ! July 2017

 400  CONTINUE

      RETURN
      END

C ================================
CDECK  ID>,  PRITERINFO. 
      SUBROUTINE PRINT_ITERINFO(CCID,ITER,COMMENT)

c print line as formated as
c  [CID](ITER=[ITER]):  [COMMENT]
c

c subroutine args
      CHARACTER CCID*(*)  ! SNID
      INTEGER   ITER
      CHARACTER COMMENT*(*)  ! comment to ptrin

c local args
      INTEGER LCCID
C -------------------- BEGIN ----------------

      LCCID = INDEX(CCID,' ') - 1
      write(6,20) CCID(1:LCCID),ITER,COMMENT
20    format(T5,A,'(ITER=',I1,'): ', A)

      RETURN
      END
C ================================
CDECK  ID>,  GTMAXFRAC. 
      REAL FUNCTION GET_FUDGE_FITERR_MAXFRAC (
     &           ITER        ! (I) fit-iteration
     &          ,ifilt_obs   ! (I) observer filter index
     &          ,TREST       ! (I) Trest (days)
     &          ,LAMREST     ! (I) rest-wavelength (Angstroms)
     &             )

c Created Jul 20 2011 by R.K
c Return MAXFRAC such that fudged error is MAXFRAC * PEAKFLUX
c Based on FUDGE_FITERR_XXX parameters.
c Evaluate MAXFRAC separeately from global FUDGEALL_XXX options
c and also from FUDGE_FITERR_XXX options.
c Return maximum of these two MAXFRAC  values  so that we
c essentially OR the two options.
c
c Feb 28 2020:
c   FIRST_ITER now includes !LREPEAT_ITER. Restore old bug
c   with RESTORE_DES3YR.
c
c -------------
      IMPLICIT NONE

c input args
      INTEGER ITER, IFILT_OBS  ! (I) fit-iter and filter index
      REAL    TREST, LAMREST   ! (I) rest epoch (days), rest-lambda(A)

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      REAL ALL_MAXFRAC, FITERR_MAXFRAC
      LOGICAL LT1, LT2, LAM1, LAM2, LFILT, LITER
      LOGICAL LT,  LAM, LFINAL, LTMP, FIRST_ITER

c functions
      LOGICAL FIRST_ITERATION
c ------------------ BEGIN ----------------

      GET_FUDGE_FITERR_MAXFRAC = 0.0
      IF ( .NOT. USE_FUDGE_FITERR ) RETURN

      FIRST_ITER = FIRST_ITERATION(ITER)

      ALL_MAXFRAC         = 0.0
      FITERR_MAXFRAC      = 0.0

c check global options first

      LTMP = ( FUDGEALL_MAXFRAC > 0.000001 )
      IF ( LTMP ) THEN
         ALL_MAXFRAC =  FUDGEALL_MAXFRAC
      ENDIF

      LTMP = (FUDGEALL_ITER1_MAXFRAC > 1.0E-9 .and. FIRST_ITER )
      IF ( LTMP ) THEN
         ALL_MAXFRAC = FUDGEALL_ITER1_MAXFRAC
      ENDIF

c ---------
c check options that depend on TREST, LAMREST and filter

      LFILT = DOFUDGE_FITERR(ifilt_obs)
      LITER = ITER .LE. FUDGE_FITERR_MAXITER

      LT1 =   TREST .GE. FUDGE_FITERR_TREST(1)
     &  .and. TREST .LE. FUDGE_FITERR_TREST(2)
      LT2 =   TREST .GE. FUDGE_FITERR_TREST(3)
     &  .and. TREST .LE. FUDGE_FITERR_TREST(4)
      LT  = LT1  .or. LT2

      LAM1 =   LAMREST .GE. FUDGE_FITERR_RESTLAM(1)
     &   .and. LAMREST .LE. FUDGE_FITERR_RESTLAM(2)
      LAM2 =   LAMREST .GE. FUDGE_FITERR_RESTLAM(3)
     &   .and. LAMREST .LE. FUDGE_FITERR_RESTLAM(4)
      LAM = LAM1 .or. LAM2


      LFINAL = (LT .and. LAM  .and. LITER .and. LFILT)
      IF( LFINAL ) THEN
         FITERR_MAXFRAC =  FUDGE_FITERR_MAXFRAC
      ENDIF

      GET_FUDGE_FITERR_MAXFRAC =  MAX(ALL_MAXFRAC,FITERR_MAXFRAC)

      RETURN
      END

C ==========================================
CDECK  ID>,  FITINI_PRIOR. 
      SUBROUTINE FITINI_PRIORS
c
c Initialize -2 * ln(prob) for prior on each fit variable.
c Fills PRIOR_CHI2GRID array so that chi2-contribution
c can be looked up via interpolation in CHI2_PRIOR function.
c
c Priors initialized for:
c  - AV     (exponential convoluted with Gaussian)
c  - MJD    (gaussian)
c  - photoZ (Gaussian -- added Dec 30, 2006)
c
c Apr 2 2018: call FITINI_FLATPRIOR for color
c
c Apr 7 2020: init AV prior for SNOOPY as well as MLCS2k2
c
c ------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER  ibin, ipar, NPRIOR

      REAL*8 tmp(2), prob, chi2, arg, xmin(2), xmax(2), xbin, x , wgt

      LOGICAL LSTAT

c histogram args

      INTEGER NB(2), LL, NDIM, LCHIS, HOFF, hid
      CHARACTER chis*80

c function

      REAL*8 CHI2_PRIOR

C -------------- BEGIN ----------

c initalize all chi2-prior to zero.

      DO ibin = 1, NBIN_PRIOR
      DO ipar = 1, IPAR_MAX
          PRIOR_CHI2GRID(ibin,ipar) = 0.0
          PRIOR_PROBGRID(ibin,ipar) = 0.0
          PRIOR_VALGRID(ibin,ipar)  = 0.0
      ENDDO
      ENDDO

c initialize prior ranges to zero

      DO ipar = 1, IPAR_MAX
         USE_PRIOR(ipar) = .FALSE.
         PRIOR_RANGE(1,ipar) = 0.0
         PRIOR_RANGE(2,ipar) = 0.0
         PRIOR_BINSIZE(ipar) = 0.0

         FLATPRIOR_RANGE(1,IPAR) = -9.E9
         FLATPRIOR_RANGE(2,IPAR) = -9.E9

         FLATPRIOR_BINRANGE(1,IPAR) = +999999
         FLATPRIOR_BINRANGE(2,IPAR) = -999999

      ENDDO
      USE_PRIOR_AV = .FALSE.

      NPRIOR = 0

c Set peak-MJD PRIOR for all models, and even if OPT_PRIOR=0.
c This is mainly to protect against crazy MJD values,
c and it is not meant to bias the fit.

      CALL FITINI_PKMJDPRIOR(LSTAT)
      IF ( LSTAT ) THEN
        NPRIOR = NPRIOR + 1
        USE_PRIOR(ipar_PEAKMJD)  = .TRUE.
      ENDIF

c check OPT_PRIOR after MJD prior is set.

      IF ( OPT_PRIOR .EQ. 0  ) GOTO 900

c - - - - - - -  -
c Set PhotoZ PRIOR for SN-photoZ fit.
c
      IF ( DOFIT_PHOTOZ ) THEN
        CALL FITINI_ZPRIOR(LSTAT)
        IF ( LSTAT ) THEN
           NPRIOR = NPRIOR + 1
           USE_PRIOR(ipar_zPHOT)  = .TRUE.
        ENDIF

        CALL FITINI_MUPRIOR(LSTAT)
        IF ( LSTAT ) THEN
           NPRIOR = NPRIOR + 1
           USE_PRIOR(ipar_DLMAG)  = .TRUE.
        ENDIF

      ENDIF

c - - - - - -  -
c now turn on prior(s) specific to model

      IF ( FITMODEL_INDEX .EQ. MODEL_MLCS2k2 .or.
     &     FITMODEL_INDEX .EQ. MODEL_SNOOPY  .or.
     &     FITMODEL_INDEX .EQ. MODEL_BAYESN ) THEN

        CALL FITINI_AVPRIOR(LSTAT)
        IF ( LSTAT ) THEN
           NPRIOR = NPRIOR + 1
           USE_PRIOR(ipar_AV) = .TRUE.  ! ambiguous for AV or SALT2c
           USE_PRIOR_AV       = .TRUE.  ! so set this AV-specific logical
        ENDIF

        ipar = IPAR_RV
        CALL FITINI_FLATPRIOR(IPAR,LSTAT)
        IF ( LSTAT ) THEN
           NPRIOR = NPRIOR + 1
           USE_PRIOR(IPAR)   = .TRUE.
        ENDIF

      ENDIF  ! end of AV-specific priors


      ipar = IPAR_SHAPE
      CALL FITINI_FLATPRIOR(IPAR,LSTAT)
      IF ( LSTAT ) THEN
         NPRIOR = NPRIOR + 1
         USE_PRIOR(IPAR)   = .TRUE.
      ENDIF


      IF ( NSHAPEPAR > 1 ) THEN
        ipar = IPAR_SHAPE2
        CALL FITINI_FLATPRIOR(IPAR,LSTAT)
        IF ( LSTAT ) THEN
           NPRIOR = NPRIOR + 1
           USE_PRIOR(IPAR)   = .TRUE.
        ENDIF
      ENDIF

      ipar = IPAR_COLOR
      CALL FITINI_FLATPRIOR(IPAR,LSTAT)
      IF ( LSTAT ) THEN
         NPRIOR = NPRIOR + 1
         USE_PRIOR(IPAR)   = .TRUE.
      ENDIF


      IF ( NPRIOR .EQ. 0 ) THEN
        CALL PRBANNER("FITINI_PRIOR: NO PRIORS DEFINED" )
      ENDIF

c -----------------------------------------
c plot chi2 from prior in monitor plot
c use CHI2_PRIOR function

900   CONTINUE
      if ( .NOT. USE_TABLEFILE ) RETURN

      NDIM = 1  ; WGT = 1.0 ! 1D histos
      HOFF = 980
      DO 50 ipar = 1, IPAR_MAX

         if ( .not. USE_PRIOR(ipar) ) goto 50

59       format( A,' from ',A,'-prior vs. ', A )

c make plot with very fine binning to check interpolation
         xbin    = 0.2*PRIOR_BINSIZE(ipar)
         xmin(1) = PRIOR_RANGE(1,IPAR) - xbin/2.0
         xmax(1) = PRIOR_RANGE(2,IPAR) + xbin/2.0
         nb(1)   = int( (xmax(1) - xmin(1) + 0.1*xbin)/xbin )


         LL = INDEX ( PARNAME_STORE(ipar), ' ' ) - 1
         LCHIS = 25+2*LL

         hid = HOFF + ipar
         write(chis,59) 'prob',
     &         PARNAME_STORE(ipar)(1:LL), PARNAME_STORE(ipar)(1:LL)
         chis = chis(1:LCHIS) // char(0)
         CALL SNHIST_INIT(NDIM, HID, CHIS, NB, xmin, xmax, 80)

         hid = HOFF + 10 + ipar
         write(chis,59) 'chi2',
     &         PARNAME_STORE(ipar)(1:LL), PARNAME_STORE(ipar)(1:LL)
         chis = chis(1:LCHIS) // char(0)
         CALL SNHIST_INIT(NDIM, HID, CHIS, NB, xmin, xmax, 80)

      DO 51 ibin = 1, NB(1)
           tmp(1)  = PRIOR_RANGE(1,IPAR) + xbin * float(ibin-1)
           chi2    = CHI2_PRIOR(ipar,tmp(1))
           arg     = min(40.0,chi2/2.0)
           prob    = dexp(-arg)

           HID = HOFF +  0 + ipar
           CALL SNHIST_FILL ( NDIM, HID, tmp, prob)

           HID = HOFF + 10 + ipar
           CALL SNHIST_FILL ( NDIM, HID, tmp, chi2 )

51    CONTINUE
50    CONTINUE

      RETURN
      END    ! end of FITINI_PRIORS


C ==========================================
CDECK  ID>,  FINI_ZPRIOR. 
      SUBROUTINE FITINI_ZPRIOR(LSTAT)
c
c Created DEc 30, 2006 by R.Kessler
c
c Initialize photoZ prior using host photoZ.
c Fills PRIOR_CHI2GRID array with Gaussian with sigma=1.0
c so that chi2-contribution can be looked up via
c interpolation in CHI2_PRIOR function.
c
c Prior chi2 =  [ (Z - Zhost) / scale*ERROR_Zhost ]^2 .
c
c where scale = PRIOR_ZERRSCALE scales the error.
c
c
c ------------------------

      IMPLICIT NONE

      LOGICAL  LSTAT  ! (O) T => prior is defined


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER IPAR, IZ

      REAL*8
     &   tmp, Zpull_BINSIZE, Zpull, XZ
     &  ,CHI2, PROB, SQSIG, SQDIF, GNORM

C -------------- BEGIN ---------------

      LSTAT    = .FALSE.
      IPAR     = IPAR_zPHOT  ! local variable

      if (BTEST(OPT_PHOTOZ, BIT_PHOTOZ_QUANTILES_STEFFEN)) then
         OPT_PHOTOZ = IBSET(OPT_PHOTOZ, BIT_PHOTOZ_QUANTILES) ! fix user mistake
      endif

      if ( BTEST(OPT_PHOTOZ,BIT_PHOTOZ_GAUSS) ) then
         write(global_banner,21) PRIOR_ZERRSCALE

      else if ( BTEST(OPT_PHOTOZ,BIT_BESTZ_GAUSS) ) then
         write(global_banner,22) PRIOR_ZERRSCALE

      else if ( BTEST(OPT_PHOTOZ,BIT_PHOTOZ_QUANTILES) ) then
        METHOD_SPLINE_QUANTILES = "CUBIC"    ! default 28 Mar, 2024
        if (btest(OPT_PHOTOZ,BIT_PHOTOZ_QUANTILES_STEFFEN)) then
          METHOD_SPLINE_QUANTILES = "STEFFEN"  ! newer option
        endif
        write(global_banner,23)
     &          PRIOR_ZERRSCALE,METHOD_SPLINE_QUANTILES
      else
        write(c1err,662) OPT_PHOTOZ
662     format('Invalid OPT_PHOTOZ = ', I5 )
        c2err = "Check &FITINP namelist."
        CALL MADABORT ( "FITINI_ZPRIOR", c1err, c2err )
      endif

21    format('INIT Gaussian HOST-PHOTOZ PRIOR with err-scale=',
     &         F7.2 )
22    format('INIT Gaussian BEST-Z PRIOR with err-scale=',
     &         F7.2 )
23    format('INIT quantile HOST-PHOTOZ PRIOR; err-scale=',
     &         F7.2,' and interp-', A8 )

      CALL PRBANNER(global_banner(1:72))

      PRIOR_RANGE(1,IPAR) = -10.0  ! min Zpull for prior
      PRIOR_RANGE(2,IPAR) = +10.0  ! max

c set up binning used to store PHOTOZ prior on grid.

      tmp = PRIOR_RANGE(2,IPAR) - PRIOR_RANGE(1,IPAR)
      Zpull_binsize = tmp / float(NBIN_PRIOR)
      PRIOR_BINSIZE(ipar) = Zpull_binsize

      SQSIG = 1.0
      GNORM = 1.0/DSQRT(2.0 * PI * SQSIG)

      DO 50 IZ     = 1, NBIN_PRIOR
            XZ     = float(IZ)  - 0.5
            Zpull  = PRIOR_RANGE(1,IPAR) + (Zpull_binsize * XZ)

            SQDIF = Zpull * Zpull
            CHI2  = SQDIF / SQSIG
            PROB  = GNORM * EXP(-CHI2/2.0)

            PRIOR_VALGRID(IZ,ipar)  = Zpull
            PRIOR_CHI2GRID(IZ,IPAR) = CHI2
            PRIOR_PROBGRID(IZ,IPAR) = PROB
50    CONTINUE

      LSTAT = .TRUE.

      RETURN
      END  ! end of FITINI_ZPRIOR

C ==========================================
CDECK  ID>,  FINI_MUPRIOR. 
      SUBROUTINE FITINI_MUPRIOR(LSTAT)
c
c Created Aug 7, 2009 by R.Kessler
c
c Initialize DISTANCE-MODULUS prior,
c Fills PRIOR_CHI2GRID array with Gaussian with sigma=1.0
c so that chi2-contribution can be looked up via
c interpolation in CHI2_PRIOR function.
c
c Prior chi2 =  [ (MU - MUREF) / scale*MUERR ]^2 .
c
c where scale = PRIOR_MUERRSCALE scales the error.
c
c WARNING: this should be used only for photoZ fits
c          to get a better estimate of redshift.
c          ==> do NOT use this for cosmology !!!
c
c ------------------------

      IMPLICIT NONE

      LOGICAL  LSTAT  ! (O) T => prior is defined


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER
     &   IPAR
     &  ,IMU

      REAL*8
     &   tmp
     &  ,pull_BINSIZE
     &  ,pull, MU
     &  ,CHI2, PROB
     &  ,SQSIG
     &  ,SQDIF
     &  ,GNORM

C -------------- BEGIN ---------------

      LSTAT    = .FALSE.
      DOPRIOR_DLMAG = ( PRIOR_MUERRSCALE .LT. 999.0 )
      IF ( .NOT. DOPRIOR_DLMAG ) RETURN

      IPAR     = IPAR_DLMAG  ! local variable

      write(global_banner,21) PRIOR_MUERRSCALE
21    format('INIT Gaussian DLMAG PRIOR with error-scale=',F6.2 )
      CALL PRBANNER(global_banner)
      print*,' '

      PRIOR_RANGE(1,IPAR) = -10.0  ! min DLMAG/DLMAGERR (not DLMAG)
      PRIOR_RANGE(2,IPAR) = +10.0  ! max

c set up binning used to store DLMAG prior on grid.

      tmp = PRIOR_RANGE(2,IPAR) - PRIOR_RANGE(1,IPAR)
      pull_binsize = tmp / float(NBIN_PRIOR)
      PRIOR_BINSIZE(ipar) = pull_binsize

      SQSIG = 1.0
      GNORM = 1.0/DSQRT(2.0 * PI * SQSIG)

      DO 50 IMU   = 1, NBIN_PRIOR
            MU    = float(IMU)  - 0.5
            pull  = PRIOR_RANGE(1,IPAR) + (pull_binsize * MU)

            SQDIF = pull * pull
            CHI2  = SQDIF / SQSIG
            PROB  = GNORM * EXP(-CHI2/2.0)

            PRIOR_VALGRID(IMU,ipar)  = pull
            PRIOR_CHI2GRID(IMU,IPAR) = CHI2
            PRIOR_PROBGRID(IMU,IPAR) = PROB
50    CONTINUE

      LSTAT = .TRUE.

      RETURN
      END  ! end of FITINI_MUPRIOR

C ==========================================
CDECK  ID>,  FINI_MJDPRIOR. 
      SUBROUTINE FITINI_PKMJDPRIOR(LSTAT)
c
c Created Aug 21, 2006 by R.Kessler
c
c Initialize MJD prior.
c Fills PRIOR_CHI2GRID array so that chi2-contribution
c can be looked up via interpolation in CHI2_PRIOR function.
c
c Prior chi2 =  [ (MJD - INIMJD) / PRIOR_MJDSIG ]^2 .
c
c This is designed to protect against crazy MJD values that
c result in FLux(model) = 0 and reasonable chi2 ...
c The MJD prior will give a big chi2 when MJD wanders off.
c
c Note that MJD really mean PEAKMJD here.
c
c Jul 16, 2008: increase storage range to +-40 instead of +-20.
c
c
c Jul 16, 2008: when MJD is withing a few days of the edge,
c               CHI2 -> CHI2 * exp[(MJD-MJDedge)^2]
c               so that the CHI2 blows up much more quickly
c               resulting in a larger slope to extrapolate.
c               This suppresses crazy MJD values in the fit.
c               Note that both CHI2 and dCHI2/dMJD are continuous
c               with this function-change.
c
c Aug 7, 2009: reduce MJD window from +-40 to +-30 and similarly
c              reduce MJD for which exponential chi2 takes over.
c
c ------------------------

      IMPLICIT NONE

      LOGICAL LSTAT  ! (O) T => prior is defined OK


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER
     &   IPAR
     &  ,IMJD

      REAL*8
     &   tmp
     &  ,MJD_BINSIZE
     &  ,XMJD
     &  ,MJD
     &  ,CHI2, PROB
     &  ,SQSIG
     &  ,SQDIF
     &  ,GNORM
     &  ,DT

c parameters (relative to initial SEARCH_PEAKMJD)

      REAL
     &   MINDEF_PKMJD1, MAXDEF_PKMJD1
     &  ,MINDEF_PKMJD2, MAXDEF_PKMJD2

      PARAMETER (
c udpated Aug 7, 2009 to handle SALT2
     &    MINDEF_PKMJD1 = -30.0   ! defined MJD-range for prior
     &   ,MAXDEF_PKMJD1 = +30.0
     &   ,MINDEF_PKMJD2 = -28.0   ! chi2 -> chi2*exp for MJD < this
     &   ,MAXDEF_PKMJD2 = +28.0   ! idem for MJD > this
     &     )

C -------------- BEGIN ---------------

      LSTAT    = .FALSE.
      IPAR     = IPAR_PEAKMJD  ! local variable

      write(global_banner,23) int(PRIOR_MJDSIG)
23    format('INIT PEAKMJD PRIOR = ', 1x ,
     &     'EXP[ -(PKMJD-PKMJD_INI)^2/', I4,'^2 ]' )

      CALL PRBANNER(global_banner(1:68))

      PRIOR_RANGE(1,IPAR) = MINDEF_PKMJD1  ! min MJD-MJD(peak) for prior
      PRIOR_RANGE(2,IPAR) = MAXDEF_PKMJD1  ! max

c set up binning used to store MJD prior on grid.

      tmp = PRIOR_RANGE(2,IPAR) - PRIOR_RANGE(1,IPAR)
      MJD_binsize = tmp / float(NBIN_PRIOR)
      PRIOR_BINSIZE(ipar) = MJD_binsize

      SQSIG = PRIOR_MJDSIG * PRIOR_MJDSIG
      GNORM = 1.0/DSQRT(2.0 * PI * SQSIG)

      DO 50 IMJD   = 1, NBIN_PRIOR
         XMJD   = float(IMJD)
         MJD    = PRIOR_RANGE(1,IPAR) + (MJD_binsize * XMJD)

         SQDIF = MJD * MJD
         CHI2  = SQDIF / SQSIG

         if ( MJD .LT. MINDEF_PKMJD2 ) then
            DT = ABS(MJD - MINDEF_PKMJD2)
         else if ( MJD .GT. MAXDEF_PKMJD2 ) then
            DT = ABS(MJD - MAXDEF_PKMJD2)
         else
            DT = 0.0
         endif

c flare the chi2 at the edges so that extrapolation
c has much larger slope. Note that CHI2 function and
c its derivative are still continuous at the MIN[MAX]DEF_PKMJD2
c boundary.

         CHI2  = CHI2 * EXP(DT*DT)
         PROB  = GNORM * EXP(-CHI2/2.0)
         PRIOR_VALGRID(IMJD,ipar)  = MJD
         PRIOR_CHI2GRID(IMJD,IPAR) = CHI2
         PRIOR_PROBGRID(IMJD,IPAR) = PROB
50    CONTINUE

      LSTAT    = .TRUE.

      RETURN
      END

C ==========================================
CDECK  ID>,  FLATPRIOR. 
      SUBROUTINE FITINI_FLATPRIOR(IPAR,LSTAT)
c
c Created Aug 2,  2007 by R.Kessler
c
c Initialize prior that is flat over defined range,
c and then has guassian roll-off.
c Fills PRIOR_CHI2GRID array so that chi2-contribution
c can be looked up via interpolation in CHI2_PRIOR function.
c
c Works for DELTA, PHOTOZ, RV
c
c Apr  2 2018: check PRIOR_COLOR_RANGE
c Oct 21 2021: allow PRIOR_COLOR_RANGE to apply to SNooPy model
c Jun 19 2023: check BAYESN model
c Jan 19 2024: check IPAR_SHAPE2
c
c ------------------------

      IMPLICIT NONE

      INTEGER IPAR   ! (I) fitpar index to define prior
      LOGICAL LSTAT  ! (O) T => prior is defined OK


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER   IVAR, LL

      REAL*8
     &   RANGE(2)
     &  ,SIGMA
     &  ,tmp
     &  ,VAR_BINSIZE
     &  ,XVAR
     &  ,VAR
     &  ,CHI2, PROB, PROBMIN
     &  ,SQSIG
     &  ,SQDIF, DIF
     &  ,ARG
     &  ,PTMP, PMIN, SIGTMP, ARGTMP
     &  ,VAR0

      character comment_prior*60
      LOGICAL LLO, LHI, DO_DELTA_PROFILE, LFLAT
      LOGICAL IS_SALT2,  IS_SNOOPY
      LOGICAL IS_SHAPE, IS_SHAPE2, IS_COLOR, IS_zPHOT
      LOGICAL IS_BAYESN, IS_MODEL_FLATCOLOR

C -------------- BEGIN ---------------

      LSTAT    = .FALSE.
      comment_prior = ' '
      LFLAT = .TRUE.  ! default is flat between Guass-rolls

      IS_SALT2  = ( FITMODEL_INDEX .EQ. MODEL_SALT2 )
      IS_SNOOPY = ( FITMODEL_INDEX .EQ. MODEL_SNOOPY )
      IS_BAYESN = ( FITMODEL_INDEX .EQ. MODEL_BAYESN )
      IS_MODEL_FLATCOLOR   = ( IS_SALT2 .or. IS_SNOOPY  )

      IS_COLOR  = ( IPAR .EQ. IPAR_COLOR  ) ! SALT2 c or AV
      IS_SHAPE  = ( IPAR .EQ. IPAR_SHAPE  )
      IS_SHAPE2 = ( IPAR .EQ. IPAR_SHAPE2 )
      IS_zPHOT  = ( IPAR .EQ. IPAR_zPHOT .and. DOFIT_PHOTOZ )

      DO_DELTA_PROFILE = IPAR .EQ. IPAR_SHAPE
     &             .and. FITMODEL_INDEX .EQ. MODEL_MLCS2k2
     &             .and. PRIOR_DELTA_PROFILE(4) .LT. 1.0

      IF ( IS_SHAPE ) THEN
          RANGE(1) = PRIOR_SHAPE_RANGE(1)
          RANGE(2) = PRIOR_SHAPE_RANGE(2)
          SIGMA    = PRIOR_SHAPE_SIGMA

          if ( DO_DELTA_PROFILE ) then
            write(comment_prior,19) PRIOR_DELTA_PROFILE
19          format('DELTA-PRIOR SIG(-,+)=',2F5.2,
     &       ', peak=',F5.2,', minProb=',F4.2)
            LFLAT = .FALSE.
          endif

      ELSE IF ( IS_SHAPE2 ) THEN  ! Jan 2024 (for D'Arcy's SALT2 x2 component
          RANGE(1) = PRIOR_SHAPE2_RANGE(1)
          RANGE(2) = PRIOR_SHAPE2_RANGE(2)
          SIGMA    = PRIOR_SHAPE2_SIGMA

      ELSE IF ( IS_COLOR .and. IS_MODEL_FLATCOLOR ) THEN  ! Apr 2 2018
          RANGE(1) = PRIOR_COLOR_RANGE(1)
          RANGE(2) = PRIOR_COLOR_RANGE(2)
          SIGMA    = PRIOR_COLOR_SIGMA

      ELSE IF ( IPAR .EQ. IPAR_RV .and. INISTP_RV .NE. 0.0) THEN
          RANGE(1) = 0.5   ! hard-wire
          RANGE(2) = 5.0
          SIGMA    = 0.1

      ELSE IF ( IPAR .EQ. IPAR_AVRV .and. INISTP_AVRV .NE. 0.0) THEN

          if ( OPT_PRIOR_AV .GT. 0 ) then
            RANGE(1) = -4.0
            RANGE(2) = +4.0
            SIGMA    = 0.02
          else
            RANGE(1) = -3.0   ! flat AV prior => negative ratio  OK
            RANGE(2) = +4.0
            SIGMA    = 0.1
          endif
      ELSE IF ( IS_zPHOT ) THEN
          RANGE(1) = PHOTOZ_RANGE_KCOR(1)
          RANGE(2) = PHOTOZ_RANGE_KCOR(2)
          SIGMA    = 0.2
      ELSE
          RETURN
      ENDIF

c -------------------------------------
      LL = INDEX( PARNAME_STORE(ipar), ' ' ) - 1
      write(global_banner,23) PARNAME_STORE(ipar)(1:LL), RANGE, SIGMA
23    format('INIT ',A,' PRIOR: ',F5.2,' to ',F5.2,
     &     '  Gauss roll sigma=',F5.2 )

      CALL PRBANNER(global_banner(1:68))
      print*,' '
      print*, '  ', comment_prior
      CALL FLUSH(6)

c define range as defined range +- 10 sigmas.

      tmp = 10. * SIGMA

      PRIOR_RANGE(1,IPAR) = RANGE(1) - tmp
      PRIOR_RANGE(2,IPAR) = RANGE(2) + tmp

      IF ( LFLAT ) THEN
        FLATPRIOR_RANGE(1,IPAR) = RANGE(1)
        FLATPRIOR_RANGE(2,IPAR) = RANGE(2)
      ENDIF

c set up binning used to store prior on grid.

      tmp = PRIOR_RANGE(2,IPAR) - PRIOR_RANGE(1,IPAR)
      VAR_binsize = tmp / float(NBIN_PRIOR)
      PRIOR_BINSIZE(ipar) = VAR_binsize

      SQSIG   = SIGMA * SIGMA
      PROBMIN = DEXP(DBLE(-700.0))  ! ~ 10^{-305}

      DO 50 IVAR   = 1, NBIN_PRIOR
         XVAR   = float(IVAR)
         VAR    = PRIOR_RANGE(1,IPAR) + (VAR_binsize * XVAR)

         LLO = VAR .LT. RANGE(1)
         LHI = VAR .GT. RANGE(2)

         IF ( LLO ) THEN
           DIF   = VAR - RANGE(1)
           SQDIF = DIF * DIF
           ARG   = 0.5 * SQDIF / SQSIG
           PROB  = DEXP(-arg)
           CHI2  = -2.0 * DLOG(prob)
         ELSE IF ( LHI ) THEN
           DIF   = VAR - RANGE(2)
           SQDIF = DIF * DIF
           ARG   = 0.5 * SQDIF / SQSIG
           PROB  = DEXP(-arg)
           CHI2  = -2.0 * DLOG(prob)
         ELSE
           CHI2  = DBLE(0.0)
           PROB  = DBLE(1.0)

c keep track of min/max bin in FLATPRIOR range;
c needed in CHI2_PRIOR to avoid discontinuity

           if ( LFLAT ) then
             FLATPRIOR_BINRANGE(1,IPAR) =
     &         MIN ( IVAR, FLATPRIOR_BINRANGE(1,IPAR) )
             FLATPRIOR_BINRANGE(2,IPAR) =
     &         MAX ( IVAR, FLATPRIOR_BINRANGE(2,IPAR) )
           endif

         ENDIF

c allow non-trivial priors to multiply flat prior

         IF ( DO_DELTA_PROFILE ) THEN
           VAR0 = PRIOR_DELTA_PROFILE(3)  ! bifurcate Gauss peak
           PMIN = PRIOR_DELTA_PROFILE(4)  ! min prob

           if ( VAR .GT. VAR0 ) then
             SIGTMP = PRIOR_DELTA_PROFILE(2) ! sig+ : dimmer SN
           else
             SIGTMP = PRIOR_DELTA_PROFILE(1) ! sig- : brighter SN
           endif
           ARGTMP = 0.5 * (VAR-VAR0)**2 / (SIGTMP*SIGTMP)

           PTMP = (1.0 - PMIN) * DEXP(-ARGTMP) + PMIN

           PROB = PROB * PTMP
           CHI2 = CHI2 - 2.0 * DLOG(PTMP)
         ENDIF

         PROB = MAX( PROB, PROBMIN )

         PRIOR_VALGRID(IVAR,ipar)  = VAR
         PRIOR_CHI2GRID(IVAR,IPAR) = CHI2
         PRIOR_PROBGRID(IVAR,IPAR) = PROB
50    CONTINUE

      LSTAT    = .TRUE.

      RETURN
      END   ! end FITINI_FLATPRIOR


C ==========================================
CDECK  ID>,  FINI_AVPRIOR. 
      SUBROUTINE FITINI_AVPRIOR(LSTAT)
c
c Initialize AV prior.
c Fills PRIOR_CHI2GRID array so that chi2-contribution
c can be looked up via interpolation in CHI2_PRIOR function.
c
c Jul 27,2007: check option for ESSENCE/WV07 prior
c
c Jun 22, 2009: check OPT_PRIOR_AV for flat-prior option
c
c Apr 28, 2011: set C2ERR when PRIOR_AVRES < 0
c
c Sep 08, 2011: FLOAT() -> DBLE()
c               REAL*8 AVRES = DBLE(PRIOR_AVRES)
c               to have consistent double precision usage.
c
c ------------------------

      IMPLICIT NONE

      LOGICAL LSTAT ! (O) T => prior is defined


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER
     &   IAV1
     &  ,IAV2
     &  ,IAVTMP
     &  ,IAV1_MIN, IAV1_MAX
     &  ,IAV2_MIN, IAV2_MAX
     &  ,iexp, NEXP
     &  ,LL(2)

      REAL*8
     &   tmp
     &  ,AV1_binsize
     &  ,AV2_binsize
     &  ,AV1, XAV1
     &  ,AV2, XAV2
     &  ,AVEXTRAP
     &  ,WAV, WRES
     &  ,AVRES
     &  ,GNORM
     &  ,prob, chi2
     &  ,tmpchi2
     &  ,probmin
     &  ,probmax
     &  ,chi2max
     &  ,chi2_1, chi2_2, chi2slope
     &  ,arg

cc      REAL*8  CHI2_PRIOR

      LOGICAL USER_EXPSUM

      CHARACTER CPRIOR(2)*28

C -------------- BEGIN ----------

      LSTAT       = .FALSE.
      NEXP        = 0
      USER_EXPSUM = .FALSE.

c determine how many exponentials used in prior.


c check for flat prior
      IF ( OPT_PRIOR_AV .EQ. 0 ) THEN
         CALL PRBANNER( 'FITINI_AVPRIOR: FLAT-NEG AV PRIOR.')
         PRIOR_AVRES    = 10.0
         PRIOR_AVWGT(1) = 75.0  ! adjusted so that probmax = 1
         NEXP           = 1
         LSTAT          = .TRUE.
         USER_EXPSUM    = .TRUE.
         GOTO 40
      ENDIF

c ------------

      DO iexp = 1, 2
        cprior(iexp) = ':'
        if ( PRIOR_AVEXP(iexp) .GT. 0.0 .and.
     &       PRIOR_AVWGT(iexp) .GT. 0.0 ) THEN
                NEXP = NEXP + 1

           write(cprior(iexp),12)
     &         PRIOR_AVWGT(iexp), PRIOR_AVEXP(iexp)
12         format( F5.2,'*EXP(-AV/',F5.3,'):' )
        endif

        LL(iexp) = INDEX ( CPRIOR(iexp), ':' ) - 1

      ENDDO

      IF ( NEXP .LE. 0 ) THEN
         CALL PRBANNER( 'FITINI_AVPRIOR: NO AV-PRIOR IS USED.' )
         RETURN
      ELSE
         write(global_banner,19) NEXP
19       format('FITINI_AVPRIOR: DEFINE AV PRIOR WITH ',
     &          I1,' EXPONENTIALS')
         CALL PRBANNER( global_banner )
         LSTAT    = .TRUE.
         USER_EXPSUM = .TRUE.
      ENDIF

c print prior formula to screen

      write(6,23)  CPRIOR(1)(1:LL(1)), CPRIOR(2)(1:LL(2))
      write(6,24)  PRIOR_AVRES
23    format(T6,'AV-PRIOR FUNCTION  = ', A, ' + ' , A )
24    format(T6,'AV-SIGMA(SMEARING) = ', F6.3 )

      print*,' '

40    CONTINUE

      AVRES  = DBLE(PRIOR_AVRES)

      if ( PRIOR_AVRES .LE. 0.0 ) then
         write(c1err,660) PRIOR_AVRES
660      format('PRIOR_AVRES = ', F9.4, ' < 0 is INVALID.   ')
         c2err = 'PRIOR_AVRES must be positive. '
         CALL MADABORT("FITINI_AVPRIOR", c1err, c2err )
      endif


      PRIOR_RANGE(1,IPAR_AV) = -1.0  ! min AV for prior
      PRIOR_RANGE(2,IPAR_AV) = +2.0  ! max AV for prior

c set up binning used to store AV prior on grid.

      tmp = PRIOR_RANGE(2,IPAR_AV) - PRIOR_RANGE(1,IPAR_AV)
      AV1_binsize = tmp / DBLE(NBIN_PRIOR)
      PRIOR_BINSIZE(ipar_AV) = AV1_binsize
      IAV1_MIN = 1
      IAV1_MAX = NBIN_PRIOR

c setup binning for Gaussian smear: bin size = smaller of
c 1/10 of sigma or AV1_binsize.
c First AV2 bin has positive AV; last AV2 bin is 3-sigma
c past range.

      AV2_binsize = min(AV1_binsize, 0.1*AVRES)

      tmp         = PRIOR_RANGE(1,IPAR_AV)
      if ( tmp .LT. 0.0 ) then
        IAV2_MIN  = int( -tmp / AV2_binsize ) - 1
      else
        IAV2_MIN  = 1
      endif

      tmp = PRIOR_RANGE(2,IPAR_AV) - PRIOR_RANGE(1,IPAR_AV)
      IAV2_MAX    = int( (tmp + 3.0*AVRES)/AV2_binsize )

c now convolve exponential AV-prior with gaussian smear
c (to allow for negative AV)
c AV1 includes unphysical AV due to smearing;
c AV2 includes only physical AV

      GNORM   = AVRES * DSQRT( DBLE(2.0) * PI )
      PROBMIN = DEXP(DBLE(-700.0))  ! ~ 10^{-305}
      CHI2MAX = 0.0

      PROBMAX = 0.0

c start with loop over AV that includes negative values.

      DO 41 IAV1  = IAV1_MIN, IAV1_MAX
         XAV1     = DBLE(IAV1)
         AV1      = PRIOR_RANGE(1,IPAR_AV) + AV1_binsize * xav1

         PRIOR_VALGRID(iav1,ipar_av) = AV1  ! store AV vs. grid index

c now loop over physical AV2 > 0, and go past defined range to
c accoount for smearing from beyond defined range.

          do 42 IAV2 = IAV2_MIN, IAV2_MAX
               XAV2  = DBLE(IAV2)
               AV2   = PRIOR_RANGE(1,IPAR_AV) + AV2_binsize * xav2

               if ( AV2 .LT. 0.0 ) goto 42

               IF ( USER_EXPSUM ) THEN
                 WAV = 0.0
                 DO iexp = 1, NEXP
                   ARG = AV2/PRIOR_AVEXP(iexp)
                   WAV = WAV + PRIOR_AVWGT(iexp) * DEXP(-arg)
                 ENDDO
               ENDIF

               if ( AVRES .GT. 1.0E-6 ) then
                  tmp   = (AV2 - AV1)/AVRES
                  WRES  = DEXP(-0.5*tmp*tmp) / GNORM
               else if ( dabs(AV2-AV1) .LT. 0.0001 ) then
                  WRES  = 1.0 / AV2_binsize
               else
                  WRES  = 0.0
               endif

               prob = WAV * WRES
               prob = MAX ( prob, probmin )

               probmax = max ( prob, probmax )

c large AVEXP is a flag to have no prior on AV
               if ( PRIOR_AVEXP(1) .GT. 100.0 ) prob = 0.0

               if ( prob .GT. 0.0 ) then

                  PRIOR_probgrid(iav1,ipar_av) =
     &            PRIOR_probgrid(iav1,ipar_av) + prob * AV2_binsize

c update chi2
                  prob    = PRIOR_probgrid(iav1,ipar_av)
                  tmpchi2 = -2.0 * dlog(prob)
                  PRIOR_chi2grid(iav1,ipar_av) = tmpchi2

               endif
42       continue  ! end of AV2 loop


41    CONTINUE   ! end of AV1 loop

c -----------------------------------------------------------
c Now check if chi2 > 1400 (at negative AV) which causes prob
c to goto zero due to floating point overflow.
c To avoid discontinuity in chi2, the chi2 is extrapolated
c from a safe region.

c get chi2max from most neg AV in 1st bin

      chi2max = PRIOR_chi2grid(1,ipar_av)

c look for first bin with chi2 < chi2max

      DO IAV1 = 2, NBIN_PRIOR
         chi2 = PRIOR_CHI2GRID(iav1,ipar_av)
         if ( chi2 .LT. 0.999*chi2max ) then
            IAVTMP = IAV1
            goto 444
         endif
      ENDDO

444   CONTINUE

c get slope from two neighbor chi2 points

      AV1 =  PRIOR_VALGRID(iavtmp,  ipar_av)
      AV2 =  PRIOR_VALGRID(iavtmp+1,ipar_av)
      AVEXTRAP = AV1

      chi2_1 = PRIOR_chi2grid(iavtmp,  ipar_av)
      chi2_2 = PRIOR_chi2grid(iavtmp+1,ipar_av)

      chi2slope = (chi2_2 - chi2_1) / (AV2-AV1)

c Loop over AV bins again, and replace chi2 in overflow region
c with extrapolated chi2.

      DO IAV1 = 1, NBIN_PRIOR
         AV1 =  PRIOR_VALGRID(iav1,ipar_av)
         if ( AV1 .LT. AVEXTRAP ) then
           chi2 = chi2_1 + chi2slope * (AV1 - AVEXTRAP)
           PRIOR_CHI2GRID(iav1,ipar_av) = chi2
         endif
      ENDDO

      CALL FLUSH(6)

      RETURN
      END  ! end of FITINI_AVPRIOR


C ==========================================
CDECK  ID>,  CHI2_PRIOR. 
      DOUBLE PRECISION FUNCTION CHI2_PRIOR(ipar, PARVAL)
c
c Return chi2 penality for prior.
c IPAR is the fitpar index;
c FITPAR is the value to look up the prior.
c
c Mar 2024: refactor to use interp_1DFUN (C fun in sntools.c)
c       and get rid of very old/obscure interpolcation code.
c
c ------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c function args.

      INTEGER IPAR    ! (I) fitpar index
      REAL*8  PARVAL  ! (I) fitpar value to compute chi2

c local var

      INTEGER OPTMASK
      CHARACTER COMMENT*40
      REAL*8    TMPVAL, MINVAL, MAXVAL

c define variables for polynomial interpolation

      REAL*8   INTERP_1DFUN
      EXTERNAL INTERP_1DFUN

      REAL*8 CHI2_PRIOR_LEGACY

C -------------- BEGIN --------------

c xxxxxxxx mark delete Apr 4 2024 xxxxxxxxxx
c      IF ( DEBUG_FLAG .NE. 1024 ) THEN  ! legacy function, Mar 2024
c          CHI2_PRIOR = CHI2_PRIOR_LEGACY(ipar, PARVAL)
c          RETURN
c      ENDIF
c xxxxxxxxxxxxxxxx end mark xxxxxxxxxxxxx

      CHI2_PRIOR = 0.0  ! init

      if ( .NOT. USE_PRIOR(ipar) ) RETURN

c - - - - - -

c check trivial case of flat-prior region
      if ( PARVAL .GE. FLATPRIOR_RANGE(1,ipar) .and.
     &     PARVAL .LE. FLATPRIOR_RANGE(2,ipar) ) then
         CHI2_PRIOR = 0.0
         RETURN
      endif

      OPTMASK = 1  ! 1=linear, 2=quadratic interp
      COMMENT = 'CHI2_PRIOR(' // PARNAME_STORE(ipar)(1:8) //  ')'

      TMPVAL = PARVAL
      MINVAL = PRIOR_VALGRID(1,IPAR)
      MAXVAL = PRIOR_VALGRID(NBIN_PRIOR,IPAR)
      IF ( PARVAL .LE. MINVAL ) THEN
         TMPVAL = MINVAL + 1.0E-6
      ENDIF
      IF ( PARVAL .GE. MAXVAL ) THEN
         TMPVAL = MAXVAL - 1.0E-6
      ENDIF

      CHI2_PRIOR = interp_1DFUN(OPTMASK, TMPVAL, NBIN_PRIOR,
     &     PRIOR_VALGRID(1,IPAR), PRIOR_CHI2GRID(1,IPAR),
     &     COMMENT//char(0), 40 )


      RETURN
      END  ! end CHI2_PRIOR


C ==========================================
CDECK  ID>,  CHI2_PRIOR_LEGACY. 
      DOUBLE PRECISION FUNCTION CHI2_PRIOR_LEGACY(ipar, PARVAL)
c
c Return chi2 penality for prior.
c IPAR is the fitpar index;
c FITPAR is the value to look up the prior.
c
c Apr 3 2018: NPINT=5 only for OPT_PRIOR_AV (not for SALT2c)
c             This fixes subtle numerical problem with new color-prior.

c ------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





c function args.

      INTEGER IPAR    ! (I) fitpar index
      REAL*8  PARVAL  ! (I) fitpar value to compute chi2

c local var

      INTEGER NPMAX, NBEDGE_LININTERP
      PARAMETER (
     &    NPMAX = 5           ! max  Ngrid points for interpolation
     &   ,NBEDGE_LININTERP =2 ! do lin-interp when this close to edge (bins)
     &       )

      INTEGER
     &   NPINT, NPHALF, ibin(NPMAX)
     &  ,ibcen, ibtmp, i

      REAL*8
     &   dif, bin, parmin, parmax
     &  ,XTMP, XLO, XHI, XBIN
     &  ,dchi2_up, dchi2_dn
     &  ,arg, prob  ! debug args

      LOGICAL LTMP, LAV, LDMP

c define variables for polynomial interpolation

      REAL*8 XINT8(NPMAX), CHI2INT8(NPMAX), R8

C -------------- BEGIN --------------

      CHI2_PRIOR_LEGACY = 0.0  ! init

      if ( .NOT. USE_PRIOR(ipar) ) RETURN

c check trivial case of flat-prior region
      if ( PARVAL .GE. FLATPRIOR_RANGE(1,ipar) .and.
     &     PARVAL .LE. FLATPRIOR_RANGE(2,ipar) ) then
         CHI2_PRIOR_LEGACY = 0.0

cc         if ( IPAR .EQ. IPAR_SHAPE2 ) then ! xxxx
cc              print*,' xxx chi2_prior=0 for ', sngl(PARVAL)
cc         endif

         RETURN
      endif

c get bin for lookup
      bin   = PRIOR_binsize(ipar)

      parmin  = PRIOR_RANGE(1,ipar) + NBEDGE_LININTERP * bin
      parmax  = PRIOR_RANGE(2,ipar) - NBEDGE_LININTERP * bin

c near the edge (defined by parmin & parmax),
c use linear interp to ensure that we get large chi2 when
c [MINUIT] parameter values are way out there.
c With parabolic interp, the function can roll over at
c very large par-values and give a small (incorrect) chi2.

      IF ( PARVAL .LE. parmin ) then  ! linear interp near lo edge
          NPINT    = 2
          ibcen    = NBEDGE_LININTERP
      ELSE IF ( PARVAL .GE. parmax ) then  ! linear interp near hi edge
          NPINT    = 2
          ibcen    = NBIN_PRIOR - NBEDGE_LININTERP

      ELSE      ! parabolic interp

         dif   = PARVAL - PRIOR_RANGE(1,ipar)
         ibcen = int( (dif-bin + 1.0E-8 ) / bin ) + 1 ! central lookup bin

c avoid edges where linear interp is done.
         if ( ibcen .LE. NBEDGE_LININTERP ) then
           ibcen = NBEDGE_LININTERP + 1
         endif

         if ( ibcen .GE. NBIN_PRIOR - NBEDGE_LININTERP ) then
           ibcen = NBIN_PRIOR - NBEDGE_LININTERP - 1
         endif

c check if we are in FLAT-PRIOR region; if so, then move out so that
c we don't have two interp bins in the flat-prior region.
c Note that PARVAL must be outside FLAT-PRIOR region to get here,
c so this is just a check of the central interp bin.

         XTMP = PRIOR_VALGRID(ibcen,ipar)

         IBTMP = FLATPRIOR_BINRANGE(1,IPAR)
         IF ( IBCEN .GE. IBTMP .and. IBCEN .LE. IBTMP+2 ) then
           IBCEN = IBCEN - 1  ! move out of flat-prior region
         ENDIF

         IBTMP = FLATPRIOR_BINRANGE(2,IPAR)
         IF ( IBCEN .LE. IBTMP .and. IBCEN .GE. IBTMP-2 ) then
           IBCEN = IBCEN + 1  ! move out of flat-prior region
         ENDIF

         if ( ibcen .LE. 0 ) then

            print*,' '
            print*,' ---------------------------------------- '
            print*,' XXXX PARMIN, PARMAX = ', PARMIN, PARMAX
            print*,' XXXX IBCEN    = ', IBCEN
            print*,' XXXX PARVAL   = ', PARVAL

            write(c1err,23) ibcen, DIF, PARNAME_STORE(ipar), parval
23          format('IBCEN=',I4,' for DIF=',F8.3,' and ',A,'=',F10.3)

            write(c2err,24)
     &          PRIOR_RANGE(1,ipar),PRIOR_RANGE(2,ipar)
     &         ,PRIOR_BINSIZE(ipar)
24          format('PRIOR_RANGE,BINSIZE=', 3F10.3 )

            CALL MADABORT ( "CHI2_PRIOR_LEGACY", c1err, c2err )
         endif

c if upstream and downstream slopes are withing 5%, use 3 interp bins;
c else use 5 interp bins near rapidly changing regions.

         dchi2_up = PRIOR_CHI2GRID(ibcen,   ipar)
     &            - PRIOR_CHI2GRID(ibcen-1, ipar)
         dchi2_dn = PRIOR_CHI2GRID(ibcen+1, ipar)
     &            - PRIOR_CHI2GRID(ibcen,   ipar)

         if ( dchi2_dn .NE. 0.0)  then
            dif = dchi2_up/dchi2_dn
         else
            dif = 1.0
         endif

         LTMP = dif.GT.0.0 .and. abs(dif-1.0) .GT. 0.05
         LAV  = (IPAR .EQ. IPAR_AV) .and. USE_PRIOR_AV
         if ( LTMP .and. LAV) then
            NPINT = NPMAX
         else
            NPINT = 3
         endif
       ENDIF

c -----------------------------

      NPHALF = (NPINT-1)/2

c load table for POLINT ... note 4-byte reals

      DO i = 1, NPMAX
        if ( i .LE. NPINT ) then
          ibin(i)     = ibcen - (NPHALF+1) + i
          XTMP        = PRIOR_VALGRID(ibin(i),ipar)   ! fitpar grid
          CHI2INT8(i) = PRIOR_CHI2GRID(ibin(i),ipar)  ! chi2 grid

c if GRID point is in a flat-prior region, pull it to the
c edge of the flat-prior region to avoid discontinuity
c Note that the chi2 need not change since it is the same
c in the flat-prior region.

          XBIN = 5. * PRIOR_BINSIZE(ipar)

          XLO  = FLATPRIOR_RANGE(1,ipar)
          LTMP = (XTMP .GT. XLO) .and. (XTMP .LT. XLO+XBIN)
          IF ( LTMP ) XTMP = XLO

          XHI  = FLATPRIOR_RANGE(2,ipar)
          LTMP = (XTMP .LT. XHI) .and. (XTMP .GT. XHI-XBIN)
          IF ( LTMP ) XTMP = XHI

          XINT8(i)    = XTMP
        else
          ibin(i)     = -9
          XINT8(i)    = 0.0
          CHI2INT8(i) = 0.0
        endif
      END DO

c call CERNLIB routine to interpolate ...
c R8 is returned.

      CALL POLINT8 ( CHI2INT8, XINT8, NPINT, PARVAL, R8 )
      CHI2_PRIOR_LEGACY = R8


      LDMP = (IPAR .EQ. -IPAR_COLOR)
      if ( LDMP ) then
         print*,' XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX '
         print*,' XXX PARNAME      = ', PARNAME_STORE(ipar),'=',PARVAL
         print*,' XXX IBCEN        = ', IBCEN
         print*,' XXX IBIN(GRID)   = ', IBIN
         print*,' XXX dchi2(up,dn) = ', SNGL(dchi2_up), SNGL(dchi2_dn)
         print*,' XXX PAR(solve)   = ', SNGL(PARVAL),' NPINT=',NPINT
         print*,' XXX PAR(GRID)    = ', (SNGL(XINT8(i)),i=1,NPMAX)
         print*,' XXX CHI2(GRID)   = ', (SNGL(CHI2INT8(i)),i=1,NPMAX)
         print*,' XXX CHI2(fun)    = ', SNGL(CHI2_PRIOR_LEGACY)
         print*,' XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX '
      endif


      RETURN
      END  ! end PRIOR_CHI2_LEGACY

C =================================
CDECK  ID>,  PRIOR_ZPULL. 
      DOUBLE PRECISION FUNCTION PRIOR_ZPULL(ZSN)
c
c Created April 20, 2007 by R.Kessler
c
c Returns ZPULL = (Z - Zref) / err
c to be used in chi2-fit function.
c
c Note namelist option
c  OPT_PHOTOZ += 1  => always use host-galaxy photoZ
c  OPT_PHOTOZ += 2  => use spectro Z when available.
c  OPT_PHOTOZ += 4  => use quantiles instead of zphot point estimate
c
c Jan 27 2018:
c  + use DOFIT_PHOTOZ_HOST to determine LPULL
c
c Mar 02 2022: load global PRIOR_PHOTOZ[_ERR]
c Apr 16 2024: set zerr floor to E-3 instead of E-5 to avoid pathologically large prior-chi2.
c
c ------------------------------------------------

      IMPLICIT NONE

      REAL*8  ZSN  ! (I) redshift in fit

c local


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      REAL*8  zPRIOR_err, zPRIOR, sqerr, Zpull, Zdif, Zsig
      LOGICAL LPULL, LPZ_PHOT, LPZ_BEST

C ------------ BEGIN -------------

      PRIOR_ZPULL = 0.0
      LPULL  = .FALSE.
      LPZ_PHOT = BTEST(MASK_PHOTOZ_SOURCE,BIT_PHOTOZ_GAUSS)
      LPZ_BEST = BTEST(MASK_PHOTOZ_SOURCE,BIT_BESTZ_GAUSS)
cc xxx mark delete     &  SNLC_REDSHIFT_ERR < QUANTILE_ZERRMIN  ! Mar  2024

      if ( LPZ_PHOT ) then  ! use host photo z point estimate
         zPRIOR     = SNHOST_ZPHOT(1)
         zPRIOR_err = SNHOST_ZPHOT_ERR(1)
         LPULL = zPRIOR_err .GT. 0.005 .and. DOFIT_PHOTOZ_HOST

      else if ( LPZ_BEST ) then        ! use final redshift
         zPRIOR      = SNLC_REDSHIFT
         zPRIOR_err  = SNLC_REDSHIFT_ERR
         LPULL       = .TRUE.
      else
        write(c1err,662) OPT_PHOTOZ
662     format('Invalid OPT_PHOTOZ = ', I5 )
        c2err = 'Check &FITINP namelist.'
        CALL MADABORT ( "PRIOR_ZPULL", c1err, c2err )
      endif

c protect against error=0
      sqerr = zPRIOR_ERR*zPRIOR_ERR
c xxx mark      zPRIOR_ERR = SQRT(sqerr + 1.0E-10)
      zPRIOR_ERR = SQRT(sqerr + 1.0E-6)

      if ( zPRIOR_ERR .LE. 1.0E-7 ) then
        write(c1err,666) zPRIOR_ERR, SNLC_CCID
666     format('zPRIOR_ERR=',G10.3,'  for CID=',A)
        c2err = 'Check REDSHIFT_FINAL'
        CALL MADABORT ( "PRIOR_ZPULL", c1err, c2err )
      endif

      if ( LPULL ) then
         Zpull = (ZSN - zPRIOR )/ (zPRIOR_err*PRIOR_ZERRSCALE)
      else
         Zdif = ZSN - PHOTOZ_RANGE_KCOR(2)
         Zsig = 0.2
         if ( Zdif > 0.0 ) then
            Zpull = Zdif / Zsig  ! prior is beyond Zrange_KCOR
         else
            Zpull = 0.0  ! no host => no prior
         endif
      endif

      PRIOR_ZPULL      =  Zpull  ! function return
      PRIOR_PHOTOZ     =  sngl(zPRIOR)       ! global
      PRIOR_PHOTOZ_ERR =  sngl(zPRIOR_ERR)   ! global

      RETURN
      END  ! end of PRIOR_ZPULL

C =================================
CDECK  ID>,  PRIOR_MUPULL. 
      DOUBLE PRECISION FUNCTION PRIOR_MUPULL(isn,ZSN,MUSN)
c
c Created Aug 7, 2009 by R.Kessler
c
c Returns MUPULL = (MU - MUref) / err^2
c to be used in chi2-fit function.
c
c ------------------------------------------------

      IMPLICIT NONE

      INTEGER isn   ! (I) SN index
      REAL*8  ZSN   ! (I) redshift
      REAL*8  MUSN  ! (I) distance modulus

c local


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      REAL*8
     &   muerr, mudif, muref, mu1, mu2
     &  ,W_SAVE, OMAT_SAVE

c functions
      REAL*8 DLMAG8_REF
C ------------ BEGIN -------------

      PRIOR_MUPULL = 0.0
      if ( .NOT. DOPRIOR_DLMAG ) RETURN

      muref = DLMAG8_REF(ZSN)

c Now get DLMAG with w shifted by its uncertainty
      W_SAVE    = W0_REF(1)
      W0_REF(1) = W0_REF(1) + W0_REF(2)
      mu1       = DLMAG8_REF(ZSN)
      W0_REF(1) = W_SAVE

c now get DLMAG with OMAT shifted by its uncertainty
      OMAT_SAVE    = OMAT_REF(1)
      OMAT_REF(1)  = OMAT_REF(1) + OMAT_REF(2)
      mu2          = DLMAG8_REF(ZSN)
      OMAT_REF(1)  = OMAT_SAVE

c now add mu-shifts in quadrature (ignore correlations)
c to get distance error.

      muerr = sqrt ( (mu1-muref)**2 + (mu2-muref)**2 )
      mudif = MUSN - muref

c inclucde user MUERRSCALE in evaluating the pull.

      PRIOR_MUPULL = mudif / (muerr * PRIOR_MUERRSCALE)


      RETURN
      END  ! end PRIOR_MUPULL

C ==========================================
CDECK  ID>,  INISIMEFF. 
      SUBROUTINE INIT_PRIOR_SIMEFF
c
c Jul 25, 2011
c Initialize simulated efficiency for prior.
c [modified from MON_SIMEFF]
c Also make plots of simulated efficiency vs. Z and
c other variables.
c
c ------------------

      IMPLICIT NONE

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SIMEFFCM. inserted below by ypatchy. 

      INTEGER
     &   MXPAR_SIMEFF
     &  ,IPAR_SIMEFF_REDSHIFT
     &  ,IPAR_SIMEFF_MWEBV

      PARAMETER (
     &   MXPAR_SIMEFF         = 10
     &  ,IPAR_SIMEFF_REDSHIFT = 51  ! much larger than IPAR_MAX
     &  ,IPAR_SIMEFF_MWEBV    = 52
     &     )


      INTEGER
     &   NPAR_SIMEFF
     &  ,IPAR_SIMEFF(MXPAR_SIMEFF)

      REAL*8  PARVAL8_SIMEFF(MXPAR_SIMEFF) ! Z, AV, DELTA, etc ...
      COMMON / SIMEFFCM4 / NPAR_SIMEFF, IPAR_SIMEFF
      COMMON / SIMEFFCM8 / PARVAL8_SIMEFF


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      INTEGER   L1, L2, ivar, ipar, NWD, MSKOPT
      CHARACTER
     &   VARNAMES*200, NAME*(MXCHAR_FILEWORD)
     &  ,SIMEFF_FILE_LOC*(MXCHAR_FILENAME), FNAM*32

      LOGICAL USE_SIMEFF

c function
      INTEGER  INIT_SIMEFFMAP, STORE_PARSE_WORDS
      EXTERNAL INIT_SIMEFFMAP, STORE_PARSE_WORDS

C ------------------- BEGIN ---------------

      IF ( OPT_PRIOR    .EQ. 0 ) RETURN

      FNAM = 'INIT_PRIOR_SIMEFF'

      USE_SIMEFF = SIMEFF_FILE .NE. ' '

      IF ( USE_SIMEFF ) THEN
         OPT_PRIOR_SIMEFF = 1
         global_banner =
     &      'INIT_PRIOR_SIMEFF: PRIOR multiplied by sim-efficiency'
      ELSE
         global_banner =
     &      'INIT_PRIOR_SIMEFF: sim-efficiency NOT used for PRIOR.'
      ENDIF

      CALL PRBANNER( global_banner(1:60) )

      IF( .NOT. USE_SIMEFF ) RETURN

c ---------------------------------------------

      L1 = INDEX(SIMEFF_FILE,' ') - 1
      SIMEFF_FILE_LOC = SIMEFF_FILE(1:L1) // CHAR(0)
      NPAR_SIMEFF = INIT_SIMEFFMAP(SIMEFF_FILE_LOC, VARNAMES)

c translate VARNAMES string into variable names and fill
c IPAR_SIMEFF array for faster lookups.

      MSKOPT = MSKOPT_PARSE_WORDS_STRING
      NWD = STORE_PARSE_WORDS(MSKOPT, VARNAMES//char(0),
     &        FNAM//char(0), 200, 32 )

      IF ( NPAR_SIMEFF .NE. NWD ) THEN
        write(c1err,601) NPAR_SIMEFF
        write(c2err,602) VARNAMES, NWD
601     format('INIT_SIMEFFMAP returned NVAR=',I2)
602     format('but VARNAMES=|', A30,'| has NWD=',I2 )
        CALL MADABORT('INIT_PRIOR_SIMEFF', C1ERR, C2ERR)
      ENDIF


      DO 200 ivar   = 1, NWD
         IPAR_SIMEFF(IVAR) = -9
         call get_PARSE_WORD_fortran(ivar, name, L1 )

c check all of the fit parameter names
         DO 201 ipar = 1, IPAR_MAX  ! loop over fit-parameters
            L2 = INDEX(PARNAME_STORE(ipar),' ') -1
            if ( L1 .NE. L2 ) goto 201
            if ( NAME(1:L1) .EQ. PARNAME_STORE(ipar)(1:L2) ) then
               IPAR_SIMEFF(IVAR) = IPAR
               GOTO 200
            endif
201      CONTINUE

c check other variables that are not in the fit-par list

         IF ( NAME(1:1) .EQ. 'Z' ) THEN
             IPAR_SIMEFF(IVAR) = IPAR_SIMEFF_REDSHIFT
             GOTO 200
         ENDIF
         IF ( NAME(1:8) .EQ. 'REDSHIFT' ) THEN
             IPAR_SIMEFF(IVAR) = IPAR_SIMEFF_REDSHIFT
             GOTO 200
         ENDIF
         IF ( NAME(1:5) .EQ. 'MWEBV' ) THEN
             IPAR_SIMEFF(IVAR) = IPAR_SIMEFF_MWEBV
             GOTO 200
         ENDIF

         C1ERR = 'Uncrecognized SIMEFF map-var: ' // NAME(1:L1)
         C2ERR = 'Check SIMEFF map file.'
         CALL MADABORT('INIT_PRIOR_SIMEFF', C1ERR, C2ERR)
200   CONTINUE


      IF ( FITMODEL_INDEX == MODEL_MLCS2k2 .and. USE_TABLEFILE ) THEN
        CALL MON_SIMEFF()
      ENDIF

      RETURN
      END     ! end of INIT_PRIOR_SIMEFF

C ===================================================
CDECK  ID>,  FITANA_CUTS. 
      SUBROUTINE FITANA_CUTS(isn, LCUTS )
c
c Apply quality cuts to fit results AFTER all fit-iterations
c have finished.
c Returns LCUTS = T if fit is acceptable.
c
c Cuts on:
c
c  * min Trest
c  * max Trest
c  * TGAPMAX & T0GAPMAX
c  * NEPOCH_FIT per filter
c  * valid LUMIPAR range
c  * all but 1 error is from MINOS
c  * DLMAG error is from MINOS
c  * ZPULL (for PHOTOZ fit only)
c  * fit prob
c  * SNRMAX & SNRMAX2
c  * SIGMACHI2
c  * FitPar and covariances
c
c
c Sep 17 2016: cut on fitted covariances; see CUTWIN_FITCOV
c
c Mar 10 2017: cut on CUTWIN_FITERRz1
c
c Jan 4 2021: check OPT_SNCID_LIST option to accept everything.
c
c ------------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c subroutine args

      INTEGER  isn     ! (I) sparse SN index
      LOGICAL  LCUTS   ! (O) T => passes cuts

c local var

      INTEGER
     &   cid, LCID, year, epoch, imjd
     &  ,ifilt, ifilt_obs, cutbit, ipar, ipar2
     &  ,ETYPE, MXERRBAD, NERRBAD, NERROK, ifitdata, NTLIST

      REAL
     &   MJD, PEAKMJD, Tobs, Trest
     &  ,TMIN,TMAX, TGAPMAX, T0GAPMAX
     &  ,XN, xval, zpull, ERR_overz1, z1, TRESTCUT, TRESTCUT_EXTEND
     &  ,TLIST(MXEPOCH)

      LOGICAL LTMP, LTMP1, LTMP2, DOFIT_SPECZ, LVBOSE, LCOV

      CHARACTER
     &   BANNER*60
     &  ,cfilt*1
     &  ,CCID*(MXCHAR_CCID)
     &  ,CLINE*72

c functions

      LOGICAL LCUTVAR

C ----------------- BEGIN ----------------

      LVBOSE = ( ISN .LE. NFIT_VERBOSE )  ! June 2013 - avoid HUGE log files

      CCID = SNLC_CCID
      LCID = ISNLC_LENCCID  ! INDEX(CCID,' ')

      if ( LVBOSE ) then
         write(BANNER,20) CCID(1:LCID)
20       format('FITANA_CUTS: APPLY FIT-CUTS TO SN ',A )
         CALL PRBANNER(BANNER)
      endif

      LCUTS = .TRUE.  ! init output argument

c Jan 4 2021
c check option to use SNCID list and skip cuts ... but always
c reject events that are pegged to the edge of the shape prior range
      if ( BTEST(OPT_SNCID_LIST,0) ) THEN
         xval = LCVAL_STORE(ipar_shape)
         if ( xval < PRIOR_SHAPE_RANGE(1) + 0.05 ) LCUTS = .FALSE.
         if ( xval > PRIOR_SHAPE_RANGE(2) - 0.05 ) LCUTS = .FALSE.
         RETURN
      endif

      DOFIT_SPECZ = .NOT. DOFIT_PHOTOZ

c ------------------------------------------------
c sanity check on PEAKMJD

      if ( PEAKMJD_SANITY(1) .EQ. 0.0 ) then
          PEAKMJD_SANITY(1) = CUTWIN_PEAKMJD(1) - 20.0
          PEAKMJD_SANITY(2) = CUTWIN_PEAKMJD(2) + 20.0
      endif

      PEAKMJD   = LCVAL_STORE(IPAR_PEAKMJD) + MJDOFF

      LTMP =  ( PEAKMJD .GT. PEAKMJD_SANITY(1) )
     &  .and. ( PEAKMJD .LT. PEAKMJD_SANITY(2) )

      IF ( LTMP ) THEN
         write(CLINE,53000) 'PEAKMJD', PEAKMJD, 'PASSES'
      ELSE
         LCUTS = .FALSE.
         write(CLINE,53000) 'PEAKMJD', PEAKMJD, 'FAILED'
      ENDIF
      if ( LVBOSE ) print*,CLINE

53000   format(T10,A18,' = ', F10.3, 1x, A, ' CUT.' )

c ------------------------------------------------
c check Tobs[rest]_min,max using fit PEAKMJD instead
c of SEARCH_PEAKMJD. Use same "cutwin_Tobs[rest]*" parameters
c that snana uses.

c loop over epochs used in fit and make TLIST array

c apply Tobs cuts

      LTMP = LCUTVAR(Tobsmin_FIT, CUTBIT_Tobsmin, LVBOSE)
      IF ( .NOT. LTMP ) LCUTS = .FALSE.

      LTMP = LCUTVAR(Tobsmax_FIT, CUTBIT_Tobsmax, LVBOSE)
      IF ( .NOT. LTMP ) LCUTS = .FALSE.

c apply Trest cuts

      LTMP = LCUTVAR(Trestmin_FIT, CUTBIT_Trestmin, LVBOSE)
      IF ( .NOT. LTMP ) LCUTS = .FALSE.

      LTMP = LCUTVAR(Trestmax_FIT, CUTBIT_Trestmax, LVBOSE)
      IF ( .NOT. LTMP ) LCUTS = .FALSE.

c apply GAP cuts

      LTMP = LCUTVAR(TGAPMAX_FIT, CUTBIT_TGAPMAX, LVBOSE )
      IF ( .NOT. LTMP ) LCUTS = .FALSE.

      LTMP = LCUTVAR(T0GAPMAX_FIT, CUTBIT_T0GAPMAX, LVBOSE)
      IF ( .NOT. LTMP ) LCUTS = .FALSE.

c -------------------------------------------------------
c Check that Trestmin/max are withing FITWIN_TREST,
c but allow slop of TRESTCUT_EXTEND.

c is this redundant with Trestmin[max]_FIT cuts above ??
c Feb 2014: skip this for photo-z fits.

      IF ( NFIT_ITERATION > 1 .and. (.not. DOFIT_PHOTOZ) ) THEN

        TRESTCUT_EXTEND = 3.0  ! extend from 2.0, Feb 2014

        xval     = Trestmin_FIT
        TrestCUT = FITWIN_TREST(1) - TRESTCUT_EXTEND
        LTMP     = ( xval .GE. Trestcut )

        if ( LTMP ) then
           write(CLINE,161) 'FITWIN_TREST(min)', xval, 'PASSES'
        else
           write(CLINE,161) 'FITWIN_TREST(min)', xval, 'FAILED'
           LCUTS = .FALSE.
        endif
        IF ( LVBOSE ) print*, CLINE

c - - - -
        xval     = Trestmax_FIT
        TrestCUT = FITWIN_TREST(2) + TRESTCUT_EXTEND
        LTMP     = ( xval .LE. Trestcut )

        if ( LTMP ) then
           write(CLINE,161) 'FITWIN_TREST(max)', xval, 'PASSES'
        else
           write(CLINE,161) 'FITWIN_TREST(max)', xval, 'FAILED'
           LCUTS = .FALSE.
        endif
        IF ( LVBOSE ) print*, CLINE

c - - - -
c  Dec 18 2017: add TRESTRANGE cut
        xval     = TrestRange_FIT
        TrestCUT = CUTWIN_TRESTRANGE(1)
        LTMP     = ( xval .GE. Trestcut )

        if ( LTMP ) then
           write(CLINE,161) 'FITWIN_TRESTRANGE', xval, 'PASSES'
        else
           write(CLINE,161) 'FITWIN_TRESTRANGE', xval, 'FAILED'
           LCUTS = .FALSE.
        endif
        IF ( LVBOSE ) print*, CLINE

      ENDIF

      CALL FLUSH(6)
c ---------------------------------
c cut on fit params

      DO 160 ipar = 1, IPAR_MAX
         if ( cutwin_fitpar(1,ipar) .LT. -9.0E7 ) goto 160
         if ( cutwin_fitpar(2,ipar) .GT. +9.0E7 ) goto 160

         xval = LCVAL_STORE(ipar)
         LTMP = xval .GE.  cutwin_fitpar(1,ipar) .and.
     &          xval .LE.  cutwin_fitpar(2,ipar)

         if ( LTMP ) then
            write(CLINE,161) PARNAME_STORE(ipar), xval, 'PASSES'
         else
            write(CLINE,161) PARNAME_STORE(ipar), xval, 'FAILED'
            LCUTS = .FALSE.
         endif
         IF( LVBOSE ) print*,CLINE

160   CONTINUE

161      format(T10,A18,' = ', G10.3, 1x, A, ' CUT.' )
162      format(T10,A18,' = ', I4,    7x, A, ' CUT.' )
163      format(T10,A18, 14x, A, ' CUT.' )

c -------------------------------------------------------
c cut on fitted COVariances (Sep 2016)

      LCOV = .TRUE.
      z1   = 1. + LCVAL_STORE(IPAR_zPHOT)

      DO 170 ipar  = 1, IPAR_MAX

c Mar 10 2017 check cut on sigma/(1+z)
         ERR_overz1 = LCERR_STORE(ipar)/z1
         LTMP  = ERR_overz1 .GE. CUTWIN_FITERRz1(1,ipar) .and.
     &           ERR_overz1 .LE. CUTWIN_FITERRz1(2,ipar)
         if ( .not. LTMP ) LCOV=.FALSE.

      DO 172 ipar2 = 1, IPAR_MAX

         xval = FITERRMAT(ipar,ipar2)
         if ( abs(xval+9.0) < 1.0E-6 ) goto 172 ! not fitted

         LTMP = xval .GE.  cutwin_fitcov(1,ipar,ipar2) .and.
     &          xval .LE.  cutwin_fitcov(2,ipar,ipar2)
         if ( .not. LTMP ) LCOV=.FALSE.

c xxxxxxxxx
c         write(6,177) ipar,ipar2, LTMP, FITERRMAT(ipar,ipar2),
c     &       cutwin_fitcov(1,ipar,ipar2), cutwin_fitcov(2,ipar,ipar2)
177      format(' xxx COVCUT(',i2,',',i2, ')=', L2, ' for COV=',G11.3,
     &          '  [CUTWIN=', G10.2, ' to ' , G10.2,']' )
c xxxxxxxxx

172   CONTINUE
170   CONTINUE

      IF ( LCOV ) THEN
        write(CLINE,163) 'FITCOV', 'PASSES'
      ELSE
        LCUTS = .FALSE.
        write(CLINE,163) 'FITCOV', 'FAILED'
      ENDIF
      IF( LVBOSE ) print*,CLINE

c -------------------------------------------------------
c cuts for PHOTOZ fits only: Zpull

      IF ( DOFIT_PHOTOZ ) THEN

         zpull = PHOTOZ_ERR_ZPULL
         LTMP = zpull .GE. FITWIN_ZPULL(1) .and.
     &          zpull .LE. FITWIN_ZPULL(2)

         if ( LTMP ) then
            write(CLINE,161) 'ZPULL', zpull, 'PASSES'
         else
            write(CLINE,161) 'ZPULL', zpull, 'FAILED'
            LCUTS = .FALSE.
         endif
         IF( LVBOSE ) print*,CLINE

      ENDIF

c -------------
c Cut on fit prob

      xval = LCPROBCHI2_STORE(1)
      LTMP = xval .GE.  fitwin_prob(1) .and.
     &       xval .LE.  fitwin_prob(2)

      if ( LTMP ) then
         write(CLINE,161) 'FITPROB', xval, 'PASSES'
      else
         write(CLINE,161) 'FITPROB', xval, 'FAILED'
         LCUTS = .FALSE.
      endif
      IF( LVBOSE ) print*,CLINE

c Cut on sigma-chi2

      xval = FITCHI2_STORE(4)
      LTMP = xval .GE. FITWIN_CHI2SIGMA(1) .and.
     &       xval .LE. FITWIN_CHI2SIGMA(2)


      IF ( DOCHI2_SIGMA .and. .NOT. LTMP ) THEN
         write(CLINE,161) 'CHI2(SIGMA)', xval, 'FAILED'
         LCUTS = .FALSE.
      ELSE
         write(CLINE,161) 'CHI2(SIGMA)', xval, 'PASSES'
      ENDIF
      IF( LVBOSE ) print*,CLINE
c -------------
c 7/13/2008 - cut on number of passbands passing SNR

      xval = float(NFILT_SNRMAX_FIT)
      LTMP = xval .GE. CUTWIN_NFILT_SNRMAX(1)

      if ( LTMP ) then
         write(CLINE,162) 'NFILT_SNRMAX', int(xval), 'PASSES'
      else
         write(CLINE,162) 'NFILT_SNRMAX', int(xval), 'FAILED'
         LCUTS = .FALSE.
      endif
      IF( LVBOSE ) print*,CLINE


c May 25, 2009 - cut on number of passbands passing 2nd SNR

      xval = float(NFILT_SNRMAX2_FIT)
      LTMP = xval .GE. CUTWIN_NFILT_SNRMAX2(1)

      if ( LTMP ) then
         write(CLINE,162) 'NFILT_SNRMAX2', int(xval), 'PASSES'
      else
         write(CLINE,162) 'NFILT_SNRMAX2', int(xval), 'FAILED'
         LCUTS = .FALSE.
      endif
      IF( LVBOSE ) print*,CLINE

c cut on Nfilt passing Trestmin & Trestmin

      xval = float(NFILT_TRESTMIN_FIT)
      LTMP = xval .GE. CUTWIN_NFILT_TRESTMIN(1)

      if ( LTMP ) then
         write(CLINE,162) 'NFILT_TRESTMIN', int(xval), 'PASSES'
      else
         write(CLINE,162) 'NFILT_TRESTMIN', int(xval), 'FAILED'
         LCUTS = .FALSE.
      endif
      IF( LVBOSE ) print*,CLINE

      xval = float(NFILT_TRESTMAX_FIT)
      LTMP = xval .GE. CUTWIN_NFILT_TRESTMAX(1)

      if ( LTMP ) then
         write(CLINE,162) 'NFILT_TRESTMAX', int(xval), 'PASSES'
      else
         write(CLINE,162) 'NFILT_TRESTMAX', int(xval), 'FAILED'
         LCUTS = .FALSE.
      endif
      IF( LVBOSE ) print*,CLINE

c -----------------------------------------------
c Allow only 1 of the errors to fail MINOS errors;
c 2 or more parabolic or BAD => skip

      MXERRBAD = 99   ! allow all bad errors
      IF ( MINOS_ERR_REQALL1 ) THEN
         MXERRBAD = 1    ! allow up to 1 bad error
      ENDIF
      IF ( MINOS_ERR_REQALL0 ) THEN
         MXERRBAD = 0    ! allow 0 bad errors
      ENDIF

c count bad-errors => number of fitpars with invalid MINOS error
c (these errors are either parabolic or crazy-valued)

      NFITPAR(0) = (NFITPAR_MN - NFIXPAR)
      NERROK     = NERRTYPE(ERRTYPE_MINOS)
      NERRBAD    = NFITPAR(0) - NERROK

      IF ( NERRBAD .LE. MXERRBAD   ) THEN
         write(CLINE,165) 'PASSES'
      ELSE
         write(CLINE,165) 'FAILED'
         LCUTS = .FALSE.
      ENDIF
      IF( LVBOSE ) print*,CLINE

165   format(T12, 'MINOS ERROR EVALUATIONS   ', A, ' CUT. ' )

c ----------------------------------------------
c require that DLMAG has MINOS-error (if requested)

      IF ( MINOS_ERR_DLMAG ) THEN
         ETYPE = ERRTYPE_STORE(IPAR_DLMAG)

         if ( ETYPE .EQ. ERRTYPE_MINOS ) then
            write(CLINE,166) 'PASSES'
         else
            write(CLINE,166) 'FAILED'
            LCUTS = .FALSE.
         endif
         IF( LVBOSE ) print*,CLINE

166      format(T12, 'VALID MINOS ERR FOR DLMAG ', A, ' CUT. ' )
      ENDIF

c ===================

      IF  ( LVBOSE ) THEN
        IF ( LCUTS ) THEN
           write(6,801) CCID(1:LCID)
 801       format(T5,'CID ',A,'  PASSES FIT-CUTS ' ,/ )
        ELSE
           write(6,901) CCID(1:LCID)
 901       format(T5,'CID ',A,'  FAILED FIT-CUTS => SKIP ', / )
        ENDIF
      ENDIF

      CALL FLUSH(6)

      RETURN
      END
C ===================================================
CDECK  ID>,  FANA_STORE. 
      SUBROUTINE FITANA_STORE()
c
c store info in  FITVAL_STORE and FITERR_STORE arrays.
c These arrays are used for generic plotting in HFFITRES.
c
c Jul 24, 2009: move fillig of hid=1 to PLOT_FITRES
c
c Aug 16, 2009: call GET_TRESTVAR to re-evaluate Trest-related variables.
c
c Aug 22, 2009: fix delmu calc to use Zspec for photoz fits & to use
c               DLMAG8_REF function
c
c Aug 25, 2009: fix DELMU for SALT2: convert x0 into MU
c Aug 12, 2010: use mB to compute MU for SALT2
c                 (instead of 30-2.5log10(x0))
c
c Dec 02, 2011: fill SNRMAX_SORT_FIT to get sorted SNRMAX among fitted filters
c Feb 11, 2012: fill FITRESTMAG arrays
c
c Dec 21, 2012: fix NaN computing DELMU when REDSHIFT = -9
c
c Feb 20 2017: refactor using new calls to SET_FITANA_STORE;
c              accomodates SNTABLE_FILTER_REMAP option.
c
c --------------------------------------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


c local var

      INTEGER
     &   IFILT, IFILT_OBS, IFILT_RST, ifitdata, iep, ipar, NPAR, i
     &  ,IERR, NTLIST,  NFILT, NFADD, isort
     &  ,FLIST(MXEPOCH)
     &  ,MODE, ORDER, NSORT, INDEX_SORT(MXFILT_OBS)  ! SORTZV args
     &  ,MASK_STORE_VAL, MASK_STORE_ERR, MASK_STORE_SUM

      REAL
     &    TLIST(MXEPOCH), XEPOCH_FIT(MXFILT_ALL)
     &   ,Tobs, Trest, MJD, PEAKMJD, z1
     &   ,MAGVAL, MAGERR, PROB_MAGDIF(2)

      REAL*8
     &   Z8, MU8REF, MU8FIT, MU8
     &  ,x08, x18, c8, S2a8, S2b8, mb8

      LOGICAL USE, LNON

c function
      REAL   LCPROBCHI2
      REAL*8 DLMAG8_REF, SALT2mBcalc

      EXTERNAL SORTFLOAT

C -------------------- BEGIN ---------------

      CALL FLUSH(6)

      NFITPAR(0) = (NFITPAR_MN - NFIXPAR)

      DO ifilt           = 0, MXFILT_OBS
         if ( ifilt > 0 ) then
            NFITPAR(ifilt)  = 0
            XEPOCH_FIT(ifilt) = FLOAT( NEPOCH_FIT(ifilt) )
         endif
         NFITDOF(ifilt)  = NEPOCH_FIT(ifilt)
     &                   - NFITPAR(ifilt)
         XNFITDOF(ifilt)   = float ( NFITDOF(ifilt) )
      END DO

c re-evaluate Trest-related variables

C set global redshift variable & local peakmjd
      REDSHIFT_FIT = LCVAL_STORE(IPAR_zPHOT)
      z1 = 1. + REDSHIFT_FIT

      PEAKMJD      = LCVAL_STORE(IPAR_PEAKMJD)

c loop over epochs used in fit: rejected epochs are excluded here.

      NTLIST = 0
      DO 100 ifitdata = 1, NFITDATA
          iep       = EPLIST_FIT(ifitdata)
          MJD       = SNLC8_MJD(iep)
          Tobs      = MJD - (PEAKMJD + MJDOFF)
          Trest     = Tobs / z1
          NTLIST    = NTLIST + 1
          TLIST(NTLIST) = Trest
          FLIST(NTLIST) = I4EP_ALL(iep,IEP_IFILT_OBS)
100   CONTINUE

      CALL GET_TRESTVAR (
     &        NTLIST, TLIST, FLIST              ! (I) Trest & IFILT arrays
     &       ,FITANA_CUTWIN_TREST               ! (I) user cutwin
     &       ,FITANA_CUTWIN_TRESTMIN            ! (I) idem
     &       ,FITANA_CUTWIN_TRESTMAX            ! (I) idem
     &       ,FITANA_CUTWIN_TREST2              ! (I) idem
     &       ,NFILT                             ! (O) Nfilt
     &       ,TRESTMIN_FIT, TRESTMAX_FIT        ! (O) Trestmin,max after fit
     &       ,NFILT_TRESTMIN_FIT                ! (O)
     &       ,NFILT_TRESTMAX_FIT                ! (O)
     &       ,NFILT_TREST2_FIT                  ! (O)
     &       ,TGAPMAX_FIT, T0GAPMAX_FIT )       ! (O)

      TRESTRANGE_FIT = TRESTMAX_FIT - TRESTMIN_FIT
      TOBSMIN_FIT = TRESTMIN_FIT * z1
      TOBSMAX_FIT = TRESTMAX_FIT * z1

c -------------------------------------------------
c get peakmags in obs and rest frames.
c Make sure to get ALL of the rest-frame filters,
c even if there is no obs filter than maps on

      if ( LTRACE ) CALL DMPTRACE("CALLING PEAKMAG_CALC(OBS)")

      DO 551 IFILT = 1, NFILTDEF_SURVEY
        ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
        USE  = USE_FILT(ifilt_obs)
        if ( USE ) then
           CALL PEAKMAG_CALC(ifilt_obs, 'OBS')
        endif
551   CONTINUE


      IF ( LREST_FITMODEL ) THEN
         if ( LTRACE ) CALL DMPTRACE("CALLING PEAKMAG_CALC(REST)")
         DO 552 IFILT = 1, NFILTDEF_REST
           IFILT_RST  = IFILTDEF_MAP_REST(ifilt)
           CALL PEAKMAG_CALC(ifilt_rst, 'REST')
552     CONTINUE
      ENDIF


c compute number of fitted filters that pass global user-SNR cut
c This accounts for fudged errors so that deweighted passbands
c are not counted in NFILT_SNRMAX_FIT.

      NFILT_SNRMAX_FIT  = 0
      NFILT_SNRMAX2_FIT = 0
      DO ifilt = 1, NFILTDEF_SURVEY
        if ( R4BAND_SNRMAX_FIT(ifilt) > CUTWIN_SNRMAX(1) ) then
           NFILT_SNRMAX_FIT = NFILT_SNRMAX_FIT + 1
        endif
        if ( R4BAND_SNRMAX_FIT(ifilt) > CUTWIN_SNRMAX2(1) ) then
           NFILT_SNRMAX2_FIT = NFILT_SNRMAX2_FIT + 1
        endif
      ENDDO

c fill SNRMAX_SORT_FIT to get sorted SNRMAX for fitted bands.

      ORDER =  -1  ! -1, 0 descending,increasing order
      CALL SORTFLOAT( NFILTDEF_SURVEY, R4BAND_SNRMAX_FIT, ORDER,
     &                 INDEX_SORT);

      DO isort  = 1, NFILTDEF_SURVEY
         ifilt  = INDEX_SORT(isort)
         SNRMAX_SORT_FIT(isort) = R4BAND_SNRMAX_FIT(ifilt)  ! for CWNT
         SNRMAX_FILT_FIT(ifilt) = R4BAND_SNRMAX_FIT(ifilt)  ! for CWNT
      ENDDO

      CALL RADIUS_CALC() ! compute RADIUS_POP

c -----------------------------------------------
c store extra info in FITVAL_STORE array so that
c all gets plotted the same way as fit-parameters.

      if ( LTRACE ) CALL DMPTRACE("START 555 LOOP in FITANA_STORE")

      NPAR = PARPTR_CHI2

c store global fit parameters: Ndof, chi2 and prob(chi2)
c Note index here is NPAR instead of ipar

      NPAR = NPAR + 1  ! Ndof
      FITVAL_STORE(NPAR) = XNFITDOF(0)
      LCVAL_STORE(NPAR)  = XNFITDOF(0)

      NPAR = NPAR + 1  ! reject epochs withing Trest range (Mar 2020)
      FITVAL_STORE(NPAR) = FLOAT(NEPOCH_REJECT2)
      LCVAL_STORE(NPAR)  = FLOAT(NEPOCH_REJECT2)

      NPAR = NPAR + 1         ! chi2
      FITVAL_STORE(NPAR) = FITCHI2_STORE(1)
      LCVAL_STORE(NPAR)  = LCCHI2_STORE(1) ! Total chi2

      NPAR = NPAR + 1             ! prior-chi2
      FITVAL_STORE(NPAR) = FITCHI2_STORE(3)
      LCVAL_STORE(NPAR)  = LCCHI2_STORE(3)

      NPAR = NPAR + 1             ! sigma-chi2
      FITVAL_STORE(NPAR) = FITCHI2_STORE(4)
      LCVAL_STORE(NPAR)  = LCCHI2_STORE(4)

      IF ( LSIM_SNANA ) THEN
        NPAR = NPAR + 1             ! SIM chi2 (Dec 2013)
        FITVAL_STORE(NPAR) = SIMCHI2_CHEAT
        LCVAL_STORE(NPAR)  = SIMCHI2_CHEAT
      ENDIF

c now the fit-probs ...

      NPAR = NPAR + 1  ! prob(chi2) including prior, before marginal.
      FITVAL_STORE(NPAR) = FITPROBCHI2_STORE(1)
      LCVAL_STORE(NPAR)  = FITPROBCHI2_STORE(1)

      NPAR = NPAR + 1  ! final prob(chi2) including prior, after marg.
      FITVAL_STORE(NPAR) = FITPROBCHI2_STORE(1) ! from fit, before marg
      LCVAL_STORE(NPAR)  = LCPROBCHI2_STORE(1)  ! after marg.

      NPAR = NPAR + 1  ! prob(chi2) excluding prior
      FITVAL_STORE(NPAR) = FITPROBCHI2_STORE(2)
      LCVAL_STORE(NPAR)  = LCPROBCHI2_STORE(2)

      NPAR = NPAR + 1      ! RADIUS_POP (Jan 2024)
      FITVAL_STORE(NPAR) = RADIUS_POP
      LCVAL_STORE(NPAR)  = RADIUS_POP

c --------------------------------------

c set store-masks. first number refers to storing VAL or error.
c Second number is to take average(4) or sum(8) for REMAPed filters.
      MASK_STORE_VAL = 1 + 4   ! VAL,AVG
      MASK_STORE_ERR = 2 + 4   ! ERR,AVG
      MASK_STORE_SUM = 1 + 8   ! VAL,SUM

      DO 555 i = 1, NFILTOBS_TABLE

        ifilt_obs  = IFILTOBS_MAP_TABLE(i)
        ifilt      = IFILT_MAP_TABLE(i)

        if ( NFILT_REMAP_TABLE == 0 ) then
          if ( .not. USE_FILT(ifilt_obs) ) goto 555
          CALL FPKRAT(ifilt_obs)  ! flux/peakFlux in rest-frame
        endif

        NFADD = 0
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_VAL, ifilt,
     &                        PEAKMAG_OBS_MODEL)
        CALL SET_FITANA_STORE(ipar, MASK_STORE_ERR, ifilt,
     &                        PEAKMAG_OBS_MODEL_ERR)

        NFADD = NFADD + 1
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_VAL, ifilt,
     &                        PEAKMAG_OBS_MODEL_ERR)

        NFADD = NFADD + 1
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_VAL, ifilt,
     &                        PEAKFLUX_OBS_MODEL )
        CALL SET_FITANA_STORE(ipar, MASK_STORE_ERR, ifilt,
     &                        PEAKFLUX_OBS_MODEL_ERR )

        if ( NFILTOBS_TABLE .GT. 20 ) GOTO 555

        NFADD = NFADD + 1
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_VAL, ifilt,
     &                        PEAKFLUX_OBS_MODEL_ERR )

        NFADD = NFADD + 1
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_SUM, ifilt,
     &                        XEPOCH_FIT )

        NFADD = NFADD + 1
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_SUM, ifilt,
     &                        LC_FITCHI2 )  ! wrong for LCVAL ???

        NFADD = NFADD + 1
        ipar = NPAR + NFADD*NFILTOBS_TABLE + i
        CALL SET_FITANA_STORE(ipar, MASK_STORE_VAL, ifilt,
     &                        LC_FITPROB )  ! wrong for MARGPROB ???

555   CONTINUE

c now load rest-frame peakmags; use pointer to find IPAR.
c Note that number of rest-frame filters could be more
c than the number of obs-frame filters.

      IF ( LREST_FITMODEL ) THEN
        do ifilt    = 1, NFILTDEF_REST
          ifilt_rst = IFILTDEF_MAP_REST(ifilt)
          ipar      = PARPTR_IFILT_REST(ifilt_rst)
          FITVAL_STORE(ipar) = PEAKMAG_REST_MODEL(ifilt_rst)
          FITERR_STORE(ipar) = PEAKMAG_REST_MODEL_ERR(ifilt_rst)
          LCVAL_STORE(ipar)  = PEAKMAG_REST_MODEL(ifilt_rst)
          LCERR_STORE(ipar)  = PEAKMAG_REST_MODEL_ERR(ifilt_rst)
        enddo
      ENDIF

c Feb 2012: optional things to store for special fits
      NPAR = PARPTR_FITRESTMAG

      IPAROFF_FITRESTMAG    = NPAR
      DO ifilt    = 1, NFILTDEF_FITRESTMAG
         CALL GET_FITRESTMAG(ifilt, MAGVAL, MAGERR) ! return magdif and its err

         NPAR     = NPAR + 1
         FITVAL_STORE(Npar) = MAGVAL
         LCVAL_STORE(Npar)  = MAGVAL

         NPAR     = NPAR + 1
         FITVAL_STORE(Npar) = MAGERR
         LCVAL_STORE(Npar)  = MAGERR
      ENDDO


      IF ( FILTER_FITMAGDIF .NE. '' ) THEN

         CALL GET_FITMAGDIF(MAGVAL, MAGERR, PROB_MAGDIF)

         NPAR   = NPAR + 1
         FITVAL_STORE(Npar) = MAGVAL
         LCVAL_STORE(Npar)  = MAGVAL
         FITERR_STORE(Npar) = MAGERR
         LCERR_STORE(Npar)  = MAGERR

         NPAR   = NPAR + 1
         FITVAL_STORE(Npar) = MAGERR
         LCVAL_STORE(Npar)  = MAGERR

         NPAR   = NPAR + 1
         FITVAL_STORE(Npar) = PROB_MAGDIF(1)  ! FITPROB, 1 filter
         LCVAL_STORE(Npar)  = PROB_MAGDIF(1)  ! FITPROB, 1 filter

         NPAR   = NPAR + 1
         FITVAL_STORE(Npar) = PROB_MAGDIF(2) ! FITPROB, other filters
         LCVAL_STORE(Npar)  = PROB_MAGDIF(2) ! FITPROB, other filters
      ENDIF


      if ( LTRACE ) CALL DMPTRACE("FINISHED 555 LOOP in FITANA_STORE")


c store delZ = zfit - zspec
      NPAR = NPAR + 1
        FITVAL_STORE(NPAR) = FITVAL_STORE(IPAR_zPHOT)
     &                     - SNLC_REDSHIFT
        FITERR_STORE(NPAR) = FITERR_STORE(IPAR_zPHOT)

        LCVAL_STORE(NPAR) = LCVAL_STORE(IPAR_zPHOT)
     &                    - SNLC_REDSHIFT
        LCERR_STORE(NPAR) = LCERR_STORE(IPAR_zPHOT)

c store DELMU = MU(fit) - MU(Zspec)
c If REDSHIFT < 0 (undefined) then use photoz

      NPAR = NPAR + 1
        Z8  = FITVAL_STORE(IPAR_zPHOT)  ! Zspec or Zphot
        MU8REF = DLMAG8_REF(Z8)

        IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
           x08  = FITVAL_STORE(IPAR_X0)
           mb8  = SALT2mbcalc(x08)
           x18  = FITVAL_STORE(IPAR_SHAPE)
           c8   = FITVAL_STORE(IPAR_COLOR)
           S2a8 = DBLE(SALT2alpha)
           S2b8 = DBLE(SALT2beta)

           MU8FIT = mb8 + S2a8*x18 - S2b8*c8 + 19.36
           MU8    = MU8FIT
        ELSE
           MU8FIT = FITVAL_STORE(IPAR_DLMAG) ! fitted MU
           MU8    = LCVAL_STORE(IPAR_DLMAG)  ! might be marginalized
        ENDIF

        FITVAL_STORE(NPAR) = MU8FIT - MU8REF
        FITERR_STORE(NPAR) = FITERR_STORE(IPAR_DLMAG)

        LCVAL_STORE(NPAR) = MU8 - MU8REF
        LCERR_STORE(NPAR) = LCERR_STORE(IPAR_DLMAG)

c store delzph for photoz fits.
c Make sure to always increment NPAR.

      NPAR = NPAR + 1
      if ( DOFIT_PHOTOZ ) THEN
        CALL PHOTOZ_STORE(NPAR)
      ENDIF

c store SALT2 mB in IPAR_MB index ..
c do NOT increment NPAR here
      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
        CALL SALT2_STORE()
      ENDIF


      IF ( NPAR .NE. NPLOTPAR ) THEN
        write(c1err,662) NPAR
662     format('Filled NPAR = ', I3, ' variables ' )

        write(c2err,663) NPLOTPAR
663     format('but expected NPLOTPAR = ', I4 )
        CALL MADABORT ( "FITANA_STORE", c1err, c2err )
      ENDIF

      RETURN
      END        ! end of FITANA_STORE

C =============================
CDECK  ID>,  SET_FITANA_STORE. 
      SUBROUTINE  SET_FITANA_STORE(IPAR,MASK_STORE, IFILT, ARRAY)

c Created Feb 2017
c
c Copy element of ARRAY into either FITVAL_STORE or FITERR_STORE,
c which are used to fill the SNTABLE.
c
c For nominal jobs, load ARRAY(ifilt) into FITVAL[ERR]_STORE[IPAR].
c But for FILTER_REMAP_TABLE, then figure out which original
c filters correspond to REMAPed IFILT.
c
      IMPLICIT NONE

c function inputs
      INTEGER
     &   IPAR        ! index to store for FITVAL_STORE and FITERR_STORE
     &  ,MASK_STORE  ! mask to store VAL or ERR array, and to take avg or sum
     &  ,IFILT       ! sparse IFILT or IFILTOBS, depending on OPT_IFILT

      REAL ARRAY(*) ! array to copy into storage

c local variables


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c +CDE,FITRESTCOM.
c +CDE,TABLEVARCOM.

      LOGICAL LOADVAL, LOADERR, DO_AVG, DO_SUM
      REAL    VAL_STORE
      INTEGER IFILTOBS_ORIG, IFILTOBS_REMAP, IFILT_REMAP
      INTEGER IFILTOBS, IFILT_ORIG, IFILT_REMAP_TMP, NFILT_STORE

C ---------- BEGIN -------------

c parse MASK_STORE bits
      LOADVAL = BTEST(MASK_STORE,0)  ! 1
      LOADERR = BTEST(MASK_STORE,1)  ! 2
      DO_AVG  = BTEST(MASK_STORE,2)  ! 4 --> for REMAP filters only
      DO_SUM  = BTEST(MASK_STORE,3)  ! 8 --> for REMAP filters only

      IF ( NFILT_REMAP_TABLE == 0 ) THEN
         VAL_STORE = ARRAY(IFILT)
         GOTO 500
      ENDIF

c -----------------------------------------------------
c if we get here, then figure out the FILTER-REMAP

      IFILT_REMAP = IFILT

c loop over original filters to see which one(s)
c were remapped onto IFILT_REMAP

      VAL_STORE = 0.0 ;  NFILT_STORE=0
      DO 100 ifilt_orig = 1, NFILTDEF_SURVEY

          IFILTOBS_ORIG = IFILTDEF_MAP_SURVEY(IFILT_ORIG)

          if ( .not. USE_FILT(ifiltobs_orig) ) goto 100

          CALL FILTER_REMAP_FETCH(IFILTOBS_ORIG,        ! (I)
     &              IFILTOBS_REMAP, IFILT_REMAP_TMP)    ! (O)

          IFILT_REMAP_TMP = IFILT_REMAP_TMP + 1 ! C -> fortran index
          IF ( IFILT_REMAP .EQ. IFILT_REMAP_TMP ) THEN
             VAL_STORE     = VAL_STORE + ARRAY(IFILT_ORIG)
             NFILT_STORE   = NFILT_STORE + 1

c xxxxxxxxxxxxxxxxxxx
c        write(6,66) IFILT_ORIG, IFILTOBS_ORIG, IFILTOBS_REMAP,
c     &             IFILT_REMAP_TMP, ARRAY(IFILT_ORIG)
c66      format(T2,'xxx IFILT_ORIG=',I2,2x,
c     &          'IFILTOBS[ORIG,REMAP]=',2I3,' IFILT_REMAP_TMP=',I2,
c     &          '  ARRAY=',F10.2 )
c xxxxxxxxxxxxxxxxxxx

          ENDIF
100   CONTINUE

      IF ( NFILT_STORE > 0 ) THEN
         IF ( DO_AVG ) THEN
           VAL_STORE = VAL_STORE / FLOAT(NFILT_STORE)
         ENDIF
      ELSE
         VAL_STORE = -9.0
      ENDIF

c ---------------
500   CONTINUE
      IF ( LOADVAL ) then
        FITVAL_STORE(IPAR) = VAL_STORE
        LCVAL_STORE(IPAR)  = VAL_STORE
      ELSE
        FITERR_STORE(IPAR) = VAL_STORE
        LCERR_STORE(IPAR)  = VAL_STORE
      ENDIF

      RETURN
      END       ! end SET_FITANA_STORE

C ==================================
CDECK  ID>,  FITERR_ADJUST. 
      SUBROUTINE FITERR_ADJUST()
c
c  Created Apr 25, 2007 by R.Kessler
c
c  If MINOS returns rediculously tiny errors,
c  then set error to a reasonable artificial error.
c  This is needed for the marginalization to work
c  properly.
c
c  Feb 7, 2008:
c    - set FITERR(IPAR) in addition to FITERR_MINUS[PLUS]
c
c    - if photoZ error is too big, trim errors
c      so that +-4 sigma does not give unphysical value
c
c Dec 16, 2011:
c   photoZ error must be at least 40% of color error.
c
c ------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





c  local var

      REAL NSIGMA, EPLUS, EMINUS, Z1tmp, Z2tmp, RTMP, ZERR
      INTEGER IPAR, ITER
      LOGICAL LBAD

c ------------- BEGIN ------------

      ITER = NFIT_ITERATION

      IPAR = IPAR_AV
      LBAD = ERRTYPE(IPAR) .EQ. ERRTYPE_BAD
      IF ( LBAD ) THEN
         EMINUS = 0.20
         EPLUS  = 0.20
         FITERR_MINUS(IPAR,ITER) = -EMINUS
         FITERR_PLUS(IPAR,ITER)  = +EPLUS
         FITERR_RATIO(IPAR,ITER) =  EPLUS / EMINUS
         FITERR(IPAR,ITER)       =  EPLUS
         print*,'  Reset BAD AV ERROR before MARG_DRIVER: CID=',
     &             SNLC_CCID
      ENDIF


      IPAR = IPAR_zPHOT
      IF ( DOFIT_PHOTOZ ) THEN

c check for tiny error
         LBAD = ERRTYPE(IPAR) .EQ. ERRTYPE_BAD
         IF ( LBAD ) THEN
           EMINUS = 0.01
           EPLUS  = 0.01
           FITERR_MINUS(IPAR,ITER) = -EMINUS
           FITERR_PLUS(IPAR,ITER)  = +EPLUS
           FITERR_RATIO(IPAR,ITER) =  EPLUS / EMINUS
           FITERR(IPAR,ITER)       =  EPLUS
           print*,'  Reset BAD PHOTOZ ERROR before MARG_DRIVER: CID=',
     &               SNLC_CCID
         ENDIF

c check for too-big error that gives Z - 4\sigma_z < 0

         Z1tmp = FITVAL(ipar,ITER)
     &         - NSIGMA_PDF * FITERR_MINUS(IPAR,ITER)
         Z2tmp = FITVAL(ipar,ITER)
     &         + NSIGMA_PDF * FITERR_PLUS(IPAR,ITER)

         LBAD  = Z1tmp .LT. INIBND(1,IPAR)
         if ( NGRID_PDF .GT. 0 .and. LBAD ) then
           EMINUS = (FITVAL(ipar,ITER)-INIBND(1,IPAR))/NSIGMA_PDF
           EPLUS  = FITERR_PLUS(IPAR,ITER)
           FITERR_MINUS(IPAR,ITER) = -EMINUS
           FITERR_RATIO(IPAR,ITER) =  EPLUS / EMINUS
           FITERR(IPAR,ITER)       =  (EMINUS + EPLUS)/2.
         endif

c Dec 2011:
c check for too-tiny error. Should be at least .4 * color error
c or at least .02.

         ZERR = FITERR(IPAR,ITER)
         RTMP = ZERR/FITERR(IPAR_COLOR,ITER)
         if ( RTMP .LT. 0.4 ) then
             ZERR = 0.4 * FITERR(IPAR_COLOR,ITER)
         endif
ccc         IF ( ZERR .LT. 0.02 ) ZERR = 0.02
         FITERR(IPAR,ITER) = ZERR

      ENDIF

      RETURN
      END


C ======================================
CDECK  ID>,  SALT2xx1. 
      DOUBLE PRECISION FUNCTION SALT2xx1(ITER,x1)
c
c Created Jun  2011 by R.Kessler
c  [code moved from FCNSNLS]
c
c SALT2xx1 is the x1 value used in the SALT2  model-error
c calculation. This value is either the same x1 value in
c the fit (if DOCHI2_SIGMA=T) or it is fixed to the x1-value
c from the previous iteration.
c
c Aug 20, 2011
c If DOFIT_PHOTOZ is set, then DOCHI2_SIGMA is automatically set;
c in this case treat x1 as if DOCHI2_SIGMA was not set.
c
c Jul 2 2013: xx1 -> 0 (instead of 1.0) when ITER=1
c
c Aug 30 2017: use FIRST_ITERTION(ITER) instead of ITER=1 .
c              Needed for SIMFIT_IDEAL option.
c
c ---------------------
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c +CDE,SNLCINP.
c +CDE,FILTCOM.


      INTEGER ITER  ! (I) fit iteration
      REAL*8  x1    ! (I) x1/stretch

c local variables
      REAL*8  xx1
      LOGICAL DOFIT_zFIX
      LOGICAL FIRST_ITERATION   ! function

c --------------- BEGIN -------------

      SALT2xx1 = -999.
      DOFIT_zFIX = (.NOT. DOFIT_PHOTOZ)

      IF ( FIRST_ITERATION(ITER)  ) then
        xx1 = 0.0    ! always fix xx1 on 1st iteration
      ELSE
         if ( DOCHI2_SIGMA .and. DOFIT_zFIX) then
             xx1 = x1
         else
             xx1 = FITVAL(IPAR_SHAPE,iter-1) ! from previous iteration
         endif
      ENDIF

      SALT2xx1 = xx1

      RETURN
      END    ! end SALT2xx1


C ======================================
CDECK  ID>,  SALT2zz. 
      DOUBLE PRECISION FUNCTION SALT2zz(ITER,z)
c
c Created Mar 2018
c
c Return redshift (zz) for SALT2 error calculation.
c Motivation is for photoz fit, fix zz = z(previous iteration),
c and use zz for SALT2 error calculation.
c
c Mar 24 2020: fix logic using local DOFIT_zFIX; needed for FITRESTMAG.
c
c ---------------------
      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c +CDE,SNLCINP.
c +CDE,FILTCOM.


      INTEGER ITER  ! (I) fit iteration
      REAL*8  z     ! (I) redshift

c local variables
      REAL*8  zz
      LOGICAL FIRST_ITER, DOFIT_zFIX
      LOGICAL FIRST_ITERATION   ! function

c --------------- BEGIN -------------

      SALT2zz = -999.
      DOFIT_zFIX = (.NOT. DOFIT_PHOTOZ)

c      FIRST_ITER = FIRST_ITERATION(ITER)  ! v10_76b and earlier
      FIRST_ITER = FIRST_ITERATION(ITER) .or. DOFIT_zFIX ! >= v10_76c

      IF ( FIRST_ITER ) then
        zz = z
      ELSE
         if ( DOCHI2_SIGMA .and. DOFIT_zFIX) then
             zz = z
         else
             zz = FITVAL(IPAR_ZPHOT,iter-1) ! from previous iteration
         endif
      ENDIF

      SALT2zz = zz

      RETURN
      END

C ========================================
CDECK  ID>,  SALT2_STORE. 
      SUBROUTINE SALT2_STORE()
c
c April 24, 2009 R.Kessler
c
c Compute mB* and its error, and store in parameter
c slot IPAR_MB.  Assumes same primary system for
c each survey/filter system.
c
c
c Nov 6, 2009:  mB -> mB - FILT_MAGPRIMARY(IFILT_BESS_B)
c               SALT2 mB* is now the same for Vega & BD17 primaries
c
c Jan 28, 2010: undo above after making more general fix in genmag_SALT2.
c
c Feb 09, 2010: set redshift to 10pc (see new SAVE_Z)
c
c Jul 27, 2010: z = ZAT10PC instead of 10.*Zat10pc.
c               No idea why there was a factor of 10 ... perhaps a debug ?
c
c Aug 11, 2010: huge simplification: just use SALT2mbcalc and get
c               rid of all the stuff for MODELMAB_CALC
c
c Sep 17 2016: load FITERRMAT
c Feb 16 2017: compute MBerr analytically (fix problem found by ChrisD)
c
c -----------------------------------------------------------

      IMPLICIT NONE

c subroutine args

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      REAL*8  mB, mbtmp, MBERR, x0, x0tmp, x0err

c functions
      REAL*8  SALT2mBcalc

c ----------- BEGIN ---------

      X0    = LCVAL_STORE(IPAR_X0)
      X0err = LCERR_STORE(IPAR_X0)

      MB    = SALT2mBcalc( X0 )
      MBERR = 2.5 * (X0err/X0)/log(10.0)
c xxx      MBERR = 2.5 * (X0err/X0)/LOGTEN

c store mB and it error, and its COV


      LCVAL_STORE(IPAR_MB)  = mb
      LCERR_STORE(IPAR_MB)  = mberr
      FITERRMAT(IPAR_MB,IPAR_MB) = mberr*mberr  ! covariance

      RETURN
      END

C =====================================
CDECK  ID>,  SETZFIT. 
      SUBROUTINE SET_REDSHIFT_FIT(ITER)

c Created Aug 12, 2009 by R.Kessler
c
c For each event, called from FITPAR_PREP to set initial REDSHIFT_FIT
c that is used to select filters & epochs.
c Most of the logic here is related to photoZ fits.
c
c ----------------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER
     &  iter  ! (I) fit iteration: 1,2, ... NFIT_ITERATION

      REAL Zhost

c ---------------- BEGIN ---------------

      REDSHIFT_FIT = SNLC_REDSHIFT  ! start with "best" Z

      PRIOR_PHOTOZ     = -9.0
      PRIOR_PHOTOZ_ERR = -9.0

c .xyz add option for using HOSTGAL_PHOTOZ ... and quantiles

      DOFIT_PHOTOZ_HOST   =  .FALSE.
      DOFIT_PHOTOZ_noHOST =  .FALSE.
c -------------------------------
      IF ( DOFIT_PHOTOZ ) THEN

c check for host photoZ

        Zhost   =  SNHOST_ZPHOT(1)
        DOFIT_PHOTOZ_HOST =
     &          Zhost .GT. 0.0
     &    .and. PRIOR_ZERRSCALE .LT. 10.0

        DOFIT_PHOTOZ_noHOST = .NOT. DOFIT_PHOTOZ_HOST

c --------------------------------------------

         if ( ITER.EQ. 1 .and. DOFIT_PHOTOZ_HOST  )  then
           REDSHIFT_FIT = ZHOST
         endif

         if ( ITER.EQ. 1 .and. DOFIT_PHOTOZ_noHOST  )  then
c leave best Z  above ; note that initial photoZ gets modified
c in FITINI_PHOTOZ before the fit starts.
         endif

c use fitted photoZ (from 1st iteration) on 2nd iteration,
c or if 1st iteration is repeated.

         IF ( iter .GT. 1 .or. LREPEAT_ITER ) THEN
           REDSHIFT_FIT = LCVAL_STORE(IPAR_zPHOT)
         ENDIF

      ENDIF

c - - - - - - -  -

      if ( LSIM_SNANA .and. USESIM_REDSHIFT ) then
        REDSHIFT_FIT = SIM_REDSHIFT_HELIO + REDSHIFT_FINAL_SHIFT
      endif

c xxxxxxxxxxxxxxxxxxxxx
c      write(6,61) iter, REDSHIFT_FIT, DOFIT_PHOTOZ_HOST
c61    format(' xxx iter=',I2,'  zFIT=',F8.4,'  DO_PHOTOZ_HOST=',L1)
c      call flush(6)
c xxxxxxxxxxxxxxxxxxxxx

      RETURN
      END   ! end SET_REDSHIFT_FIT

C ========================================
CDECK  ID>,  PHZSTORE. 
      SUBROUTINE PHOTOZ_STORE(NPAR)
c
c Store PHOTOZ-related variables
c
c Mar 2024: use MASK_PHOTOZ_SOURCE instead of user-input OPT_PHOTOZ
c           because MASK_PHOTOZ_SOURCE is guaranteed to have only
c           one bit set, thus simplifying local logic.
c
      IMPLICIT NONE

      INTEGER  NPAR   ! (I) storage index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c local var

      REAL
     &   zfit,  zfiterr
     &  ,zhost, zhosterr
     &  ,zmagerr
     &  ,zdif, zerr, zpull, Z1
     &  ,TCOR

      INTEGER NFTMIN, NFTMAX

      REAL*8  MU8(2), Z8(2), DZ8, DZDMU, MUREF

      character CZPRIOR*12
      LOGICAL LPZ_PHOT, LPZ_BEST, LPZ_QUANTILE
c functions

      REAL*8  DLMAG8_REF

C ------------ BEGIN -----------

      if ( LTRACE ) CALL DMPTRACE("BEGIN PHOTOZ_STORE" )

c extract fit photoZ and determine total error.

      zfit    = LCVAL_STORE(IPAR_zPHOT)
      zfiterr = LCERR_STORE(IPAR_zPHOT)

      LPZ_PHOT     = BTEST(MASK_PHOTOZ_SOURCE,BIT_PHOTOZ_GAUSS)
      LPZ_BEST     = BTEST(MASK_PHOTOZ_SOURCE,BIT_BESTZ_GAUSS)
      LPZ_QUANTILE = BTEST(MASK_PHOTOZ_SOURCE,BIT_PHOTOZ_QUANTILES)

      if ( LPZ_PHOT ) then
        zhost    =  SNHOST_ZPHOT(1)
        zhosterr =  SNHOST_ZPHOT_ERR(1)
        czprior  = 'HOST-Gauss'   ! for screen dump comment

      else if ( LPZ_BEST ) then
        zhost    = SNLC_REDSHIFT
        zhosterr = SNLC_REDSHIFT_ERR
        czprior  = 'zBEST-Gauss'   ! for screen dump comment

      else if ( LPZ_QUANTILE ) then ! Jan 2024
        zhost    = SNHOST_QZPHOT_MEAN(1)
        zhosterr = SNHOST_QZPHOT_STD(1)
        czprior  = 'QUANTILES'   ! for screen dump comment

      endif

c scale the error by user-scale:
      zhosterr = zhosterr * PRIOR_ZERRSCALE
      if ( zhost < 0.0 .or. Zhosterr < 0.0 .or.
     &     DOFIT_PHOTOZ_noHOST) then
         zhost    = zfit
         zhosterr = 0.0
      endif

c ---------------------
c Compute photoZ-error from intrinsic MAG-dispersion.

      DZ8   = 0.01
      Z8(1) = dble(Zfit)
      Z8(2) = Z8(1) + dZ8

      MU8(1) = DLMAG8_REF(Z8(1))
      MU8(2) = DLMAG8_REF(Z8(2))
      MUREF  = MU8(1)

      DZDMU = ( Z8(2) - Z8(1) ) / ( MU8(1) - MU8(2) )  ! local derivative

      zmagerr = SNMAGRMS_for_PHOTOZ * abs(DZDMU)

c -------
      zdif  = zfit - zhost
      zerr  = sqrt ( zfiterr**2 + zhosterr**2 + zmagerr**2)
      zerr  = max(zerr,0.00001)  ! avoid Zpull divide-by-zero
      zpull = zdif / zerr

      LCVAL_STORE(Npar) = zdif
      LCERR_STORE(Npar) = zerr
      ISTORE_ZPULL          = NPAR    ! store this index for later

c store errors in common block

      PHOTOZ_ERR_SNFIT  = zfiterr
      PHOTOZ_ERR_SNHOST = zhosterr
      PHOTOZ_ERR_SNMAG  = zmagerr
      PHOTOZ_ERR_ZPULL  = zpull

c ----------------------------------------------
c print PHOTOZ info

      IF ( STDOUT_UPDATE ) THEN
        write(6,20) SNLC_CID, ZFIT
     &   , PHOTOZ_ERR_SNFIT
     &   , PHOTOZ_ERR_SNMAG

        write(6,30) SNLC_CID, CZPRIOR, ZHOST
     &   , PHOTOZ_ERR_SNHOST
     &   , PHOTOZ_ERR_ZPULL
      ENDIF

20    format(T8,'CID',I8,' PHOTOZ(SNFIT) = ', F6.4
     &         , ' +- ',F5.4,'(stat)'
     &         , ' +- ',F5.4,'(snmag)'  )

30    format(T8,'CID',I8,' ZPRIOR(',A,') = ', F6.4
     &         , ' +- ',F5.4, 5x,'ZPULL=',F6.2 )

      if ( LTRACE ) CALL DMPTRACE("END PHOTOZ_STORE")

c -----------
c for photoZ fit, MU is fixed to initial photoZ.
c Here we change the 'fixed' DLMAG parameter to correspond
c to the final (fitted) photoZ. This is just for internal
c consistency and it does not affect the fit or analysis
c in any way.

      IF ( DOFIT_PHOTOZ .and. INISTP_DLMAG .EQ. 0.0 ) THEN
         LCVAL_STORE(IPAR_DLMAG) = MUREF
      ENDIF

      RETURN
      END

C ===================================================
CDECK  ID>,  FANA_SUMMARY. 
      SUBROUTINE FITANA_SUMMARY ( isn )
c
c print summary of fit vs. filter.
c
c
c Apr 26, 2007: print marginalized chi2
c
c Mar 12, 2008: write SIMEFF(z,AV,DELTA) at end.
c
c Jul 14, 2008: define IFMINsp & IFMAXsp, and fix
c               ifilt-ranges for some write statements.
c
c Dec 15, 2008: print correct EP_XTMW instead of SNLC_XTINCMAG_MW ;
c               latter is for SDSS galaxy and is usually zero;
c               EP_XTMW is for SN.
c
c Feb 16, 2009: 'quantity' printouts account for non-sequential filters
c Apr 24, 2009: write mB +- mBerr for SALT2 model
c
c May 8, 2009: CCHI2(3) -> CCHI2(4) to include CHI2 from ln(sigma)
c
c Jul 17, 2009: add RV8 to call to SNLC_SIMEFF
c
c Jul 25, 2011: replace SNLC_SIMEFF() with SNLC_FIT_SIMEFF()
c
c Jun 27, 2013: bail when ISN > 1000
c
c --------------------------------------------------

      IMPLICIT NONE

      INTEGER isn ! (I)  sn index


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================
c +CDE,SNLCINP.

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c local var

      REAL
     &   TCOR
     &  ,RTMP(MXFILT_ALL,10)

      INTEGER
     &   ifilt, kk, i, ipar
     &  ,ifilt_obs
     &  ,NFILT, NFTMP
     &  ,IERR
     &  ,ITMP(MXFILT_ALL,10)
     &  ,NTMP

      CHARACTER
     &   BANNER*60
     &  ,CCID*(MXCHAR_CCID)
     &  ,CCHI2(4)*8
     &  ,CFILT(MXFILT_ALL)*1

      REAL*8  EFF8, LCVAL8(MXFITPAR)

      DATA  CCHI2 / 'TOTAL' , 'DATA', 'PRIOR', 'SIGMA' /

c function
      REAL*8 SNLC_FIT_SIMEFF

C ------------------- BEGIN -----------------

      IF ( ISN > NFIT_VERBOSE ) RETURN  ! Jun 2013: avoid HUGE log files.

      CCID = SNLC_CCID
      KK   = ISNLC_LENCCID

      write(BANNER,20) CCID(1:KK)
20    format('LC FIT SUMMARY for CID=', A )

      CALL PRBANNER ( BANNER )

c create sparse arrays for printing results-vs-filter on one line.

      NFILT = 0
      DO 444 ifilt   = 1, NFILTDEF_SURVEY
        IFILT_OBS    = IFILTDEF_MAP_SURVEY(ifilt)

        if ( .NOT. USE_FILT(ifilt_obs) ) goto 444

        NFILT = NFILT + 1
        CFILT(Nfilt)  = filtdef_string(ifilt_obs:ifilt_obs)
        ITMP(Nfilt,1) = NEPOCH_ALL(ifilt)
        ITMP(Nfilt,2) = NEPOCH_REJECT(ifilt)
        ITMP(Nfilt,3) = NFITDOF(ifilt)

        RTMP(Nfilt,1) = LC_MARGCHI2(ifilt)
        RTMP(Nfilt,2) = LC_MARGPROB(ifilt)
        RTMP(Nfilt,3) = PEAKMAG_OBS_MODEL(ifilt)
        RTMP(Nfilt,4) = PEAKMAG_OBS_MODEL_ERR(ifilt)
        RTMP(Nfilt,5) = SNLC_MWXT_MAG(ifilt)
        RTMP(Nfilt,6) = SNLC_MWXT_MAGERR(ifilt)

444   CONTINUE

c print no more than 6 filters to avoid a messsy output
      NFTMP = MIN(NFILT,6)

      write(6,700) 'Quantity', (CFILT(ifilt), ifilt = 1, NFTMP )
      write(6,799)
      write(6,706) 'NEPOCH',  (ITMP(ifilt,1),ifilt=1, NFTMP)
      write(6,706) 'NREJECT', (ITMP(ifilt,2),ifilt=1, NFTMP)
      write(6,706) 'NDOF',    (ITMP(ifilt,3),ifilt=1, NFTMP)

      write(6,725) 'CHI2',    (RTMP(ifilt,1), ifilt=1,NFTMP)
      write(6,725) 'PROB',    (RTMP(ifilt,2), ifilt=1,NFTMP)
      write(6,725) 'PeakMag', (RTMP(ifilt,3), ifilt=1,NFTMP)
      write(6,725) 'PeakErr', (RTMP(ifilt,4), ifilt=1,NFTMP)
      write(6,725) 'XTMW',    (RTMP(ifilt,5), ifilt=1,NFTMP)
      write(6,725) 'XTMWerr', (RTMP(ifilt,6), ifilt=1,NFTMP)

700   format(T2, A,  6(10x,A)  )
706   format(T2, A8, 6(I11)   )
725   format(T2, A8, 6(F11.2) )
799   format(T2, 80('-') )

      write(6,799)

      if ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) then
        write(6,21)
     &     CCID(1:KK)
     &    ,LCVAL_STORE(IPAR_MB)
     &    ,LCERR_STORE(IPAR_MB)
21      format(T4,'SALT2 mB(',A,') = ', F9.4, ' +- ', F7.4 )
      endif

c write Trest fit range relative to PEAKMJD(fit)

      write(6,770) CCID(1:KK), R4SN_Tearly, R4SN_Tlate, 'FIT'
      write(6,771) CCID(1:KK), R4SN_MJDmin, R4SN_MJDmax


c write Trest fit range relative to exact SIM_PEAKMJD

      IF ( LSIM_SNANA ) THEN
         TCOR = FITVAL_STORE(IPAR_PEAKMJD) - (SIM_PEAKMJD-MJDOFF)
         write(6,770) CCID(1:KK),
     &          R4SN_Tearly+TCOR, R4SN_Tlate+TCOR, 'SIM'
      ENDIF

770   format(T4, 'Trest FIT RANGE(',A,'): ', F7.2,' to ', F7.2,
     &    3x,'(relative to ',A,'-PEAKMJD)' )

771   format(T4, 'MJD   FIT RANGE(',A,'): ', F7.1,' to ', F7.1 )

c write  rest-frame peakmags


777   format(T4, A, '(',A,') : ',  $)
778   format(F6.2, $ )

c -----------------------------------
c print chi2 and prob for 1:TOTAL,  2:DATA,  3:PRIOR,   4:SIGMA

      print*,' '

      NTMP = 3
      IF ( DOCHI2_SIGMA ) NTMP=4
      DO i = 1, NTMP
         write(6,781) 'FIT MINIMUM ', CCID(1:KK)
     &    ,CCHI2(i)
     &    ,FITCHI2_STORE(i), NDOF_STORE(i)
     &    ,FITPROBCHI2_STORE(i)
      ENDDO

      IF ( NGRID_PDF .GT. 0 ) THEN
        DO i = 1, NTMP
         write(6,781) 'MARGINALIZATION', CCID(1:KK)
     &    ,CCHI2(i)
     &    ,LCCHI2_STORE(i), NDOF_STORE(i)
     &    ,LCPROBCHI2_STORE(i)
        ENDDO
      ENDIF

781   format(T4,A,'(',A,') returns ',A6,2x,
     &   'CHI2/dof=',G10.3,'/',I3,  3x, 'PROB=',F7.5)


c write simulated efficiency if used in prior.
      IF ( OPT_PRIOR_SIMEFF .GT. 0 ) THEN
        do ipar = 1, IPAR_MAX
          LCVAL8(ipar) = DBLE( LCVAL_STORE(ipar) )
        enddo
        EFF8 = SNLC_FIT_SIMEFF(isn, LCVAL8 )
        write(6,801) EFF8
801     format(T4,'SIMEFF(Best Fit) = ', F5.3)
      ENDIF

      print*,' '

      CALL FLUSH(6)

      RETURN
      END  ! end of FNANA_SUMMARY

C ========================================
CDECK  ID>,  LCPROBCHI2. 
      REAL FUNCTION LCPROBCHI2(ifilt)
      IMPLICIT  NONE
      INTEGER   IFILT  ! (I) filter index

c Mar 2011: protect againt chi2 < 0.

c local


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      REAL    probtmp, chi2
      INTEGER Ndof

      REAL*8  CHI8

c function
      REAL*8 PROB_CHI2NDOF

C ----------------- BEGIN -----------------

      LCPROBCHI2 = 0.0

      chi2     = LC_FITCHI2(ifilt)
      Ndof     = NFITDOF(ifilt)

      if ( Ndof .LE. 0 ) then
        write(6,20) Ndof, ifilt
20      format(T10,'LCPROBCHI2 WARNING: Ndof=',I2,' for ifilt=',I2 )
        return
      endif


      CHI8     = DBLE(CHI2)
      probtmp  = SNGL( PROB_CHI2NDOF(CHI8,NDOF) )

      probtmp  = max ( probtmp, 1.2E-10 )

      LCPROBCHI2 = probtmp

      RETURN
      END

C ====================================
CDECK  ID>,  FPKRAT. 
      SUBROUTINE FPKRAT(ifilt_obs)

c Created May 15, 2008 by R.Kessler
c
c Fill EP_FPKRAT[ERR] = flux/peakFlux in rest frame.
c Loop over all epochs & filters inside here.
c
c Mar 06, 2009:
c   Correct peakFlux for average data/model ratio so that
c   peakFlux is not way off if the model is off.
c   See new namelist varaible TREST_PEAKKRENORM
c   Fills new array FPKRAW to keep track of raw
c   (uncorrected) Flux/peakFlux ratio.
c
c   Pass 'ifilt_obs' arg and process only this filter
c
c Mar 3, 2010: apply K-correction only if kcor != NULLVALL;
c              ==> give something reasonable for SALT2
c
c Mar 5, 2010: fix aweful bug, argument of PEAKFLUX_OBS_MODEL
c              is IFILT_OBS instead of IFILT. Previous code worked
c              by accident for SDSS, but not for any other survey.
c
c Dec 14, 2011: avoid divide-by-zero for Fraterr calc
c
c Nov 10 2015: move divide-by-zero protection; see Flux_model
c
c --------------------

      IMPLICIT NONE

c subroutine args.

      INTEGER  IFILT_OBS    ! (I) obs filter to process
c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IMJD, ifilt, ifilto, ifiltr, iep, ifitdata

      REAL
     &   kcor, flux, flux_err, Flux_model, Flux_model_err
     &  ,Frat, Fraterr, arg, FPKRAW(MXEPOCH)
     &  ,z1, Trest, MJD, PEAKMJD
     &  ,Tnear, Terr, ratio, ratio_err, sum_ratio, wsum_ratio
     &  ,wgt, sq1, sq2, PEAK_MODEL_RENORM

      LOGICAL LRENORM, USE_RENORM, LDMP, LKCOR

      CHARACTER cfilt*1

C ---------------- BEGIN ------------

      LDMP = .FALSE.  ! debug-dump flag
      USE_RENORM = .FALSE.

      cfilt   = filtdef_string(ifilt_obs:ifilt_obs)
      z1      = 1. + REDSHIFT_FIT
      PEAKMJD = LCVAL_STORE(IPAR_PEAKMJD) + MJDOFF

        SUM_RATIO   = 0.
        WSUM_RATIO  = 0.
        Tnear       = 99999.  ! epoch closest to peak

      DO 50 ifitdata = 1, NFITDATA

         iep        = EPLIST_FIT(ifitdata)

         ifilto     = I4EP_ALL(iep,IEP_IFILT_OBS)
         if ( ifilto .NE. IFILT_OBS ) goto 50

         MJD        = R8EP_MJD(ifitdata)
         Trest      = (MJD - PEAKMJD) / z1
         ifilt      = I4EP_ALL(iep,IEP_IFILT)

         Flux           = R4EP_ALL(iep,JEP_DATAFLUX)
         Flux_err       = R4EP_ALL(iep,JEP_DATAFLUX_ERR)
         Flux_model     = R4EP_ALL(iep,JEP_MODELFLUX)
         Flux_model_err = R4EP_ALL(iep,JEP_MODELFLUX_ERR)
         kcor           = R4EP_ALL(iep,JEP_KCOR)

c Compute FPKRAT:
         Frat = Flux / PEAKFLUX_OBS_MODEL(ifilt)  ! obs-frame

c now K-correct from obs-frame back to rest-frame
         LKCOR = abs(kcor-NULLVAL) > 1.0
         IF ( LREST_FITMODEL .and. LKCOR ) then
           arg     = 0.4 * (kcor - PEAK_KCOR_MODEL(ifilt))
           Frat    = Frat * TEN8**(arg)
         ENDIF

c include data and model error for error on FPKRAT:
         if ( FLux > 0.0 .or.  flux_model > 0.0 ) then
           SQ1 = (flux_err/Flux)**2
           SQ2 = (flux_model_err/flux_model)**2
           Fraterr = Frat * sqrt(SQ1+SQ2)
         ELSE
           Fraterr = -9.0
         ENDIF

         FPKRAW(iep)                 = Frat
         R4EP_ALL(iep,JEP_FPKRAT)    = Frat
         R4EP_ALL(iep,JEP_FPKRATERR) = Fraterr

c 3/06/2009:
c check if this epoch is used to re-normalize
c the peak from the model.

         LRENORM  = Trest .GE. TREST_PEAKRENORM(1) .and.
     &              Trest .LE. TREST_PEAKRENORM(2) .and.
     &              Flux_model > 0.0   ! Nov 10 2015 - avoid divide-by-0

         IF ( LRENORM ) THEN
           USE_RENORM = .TRUE.
           ratio       = Flux/Flux_model
           ratio_err   = Flux_err/Flux_model

c Amplify error away from peak;
c error scale is 1 at peak, and 3 at 8 days away from peak.

           ratio_err   = ratio_err * sqrt(abs(Trest)+1.)

c compute weight at this epoch
           wgt         = 1. / (ratio_err**2)

c now add additional weight based on
c proximity to peak
           wgt = wgt + .01/(abs(Trest) + 1.0)

           WSUM_RATIO  = WSUM_RATIO  + wgt
           SUM_RATIO   = SUM_RATIO   + wgt * ratio

           if ( LDMP ) then
              write(6,660) cfilt, ratio, ratio_err, Trest
660           format(' xxxx ',A,'-Data/Model ratio = ',
     &             F6.3,' +- ', F6.3,'  at Trest=',F5.1,' days ' )
           endif

           if ( abs(Trest) .LT. abs(Tnear) ) then
              Tnear = Trest
           endif
         ENDIF

50    CONTINUE


c --------
c Check if model peakFlux gets renormalized

      IF ( USE_RENORM .and. WSUM_RATIO > 0.0 ) THEN

        PEAK_MODEL_RENORM = (SUM_RATIO/WSUM_RATIO)

        PEAKFLUX_OBS_MODEL_COR(ifilt) = PEAK_MODEL_RENORM

        write(6,71) SNLC_CCID, PEAK_MODEL_RENORM, cfilt
71      format(T5,'Model peakFlux(SN ', A8, ') adjusted by ',
     &          F6.3,' for FPKRAT-', A )

c adjust all of the FPKRAT values.

        DO 70 ifitdata = 1, NFITDATA

           iep     = EPLIST_FIT(ifitdata)

           ifilto  = I4EP_ALL(iep,IEP_IFILT_OBS)
           if ( ifilto .NE. IFILT_OBS ) goto 70

           R4EP_ALL(iep,JEP_FPKRAT) =
     &          FPKRAW(iep) / PEAK_MODEL_RENORM

           R4EP_ALL(iep,JEP_FPKRATERR) =
     &          R4EP_ALL(iep,JEP_FPKRATERR) / PEAK_MODEL_RENORM
 70     CONTINUE
      ENDIF

      RETURN
      END  ! FPKRAT

C =====================================
CDECK  ID>,  RADIUS_CALC. 
      SUBROUTINE RADIUS_CALC()

c Created Jan 2024
c Compute population radius RADIUS_POP in space of stretch and color.
c This variable is useful to reduce non-SNIa contamination.

      IMPLICIT NONE

      INTEGER i
      REAL s, c, s_scale, c_scale

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.cars inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )




c+CDE,FILTCOM.

C ------------ BEGIN -------------

      RADIUS_POP = -9.0  ! init to undefined
      s = LCVAL_STORE(IPAR_SHAPE)
      c = LCVAL_STORE(IPAR_COLOR)

      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
          s_scale = 3.0
          c_scale = 0.3
      ELSE
          RETURN
      ENDIF

      RADIUS_POP = sqrt( (s/s_scale)**2 + (c/c_scale)**2 )

      RETURN
      END   ! RADIUS_CALC

C ======================================
CDECK  ID>,  MODELMAG_CALC. 
      SUBROUTINE MODELMAG_CALC (
     &    IFILT          ! (I) absolute filter index
     &   ,CFRAME         ! (I) 'REST'  or 'REST2' or 'OBS'
     &   ,MJD            ! (I) MJD to evaluate
     &   ,FLUX, FLUXERR  ! (O) Flux and error
     &   ,MAG,  MAGERR   ! (O) mag and its error
     &   ,KCOR           ! (O) K-correction (if used)
     &       )

c -----------------------
c
c Created Jan 2008 by R.Kessler
c Calculate Lightcurve parmaters at MJD using best fit model.
c Returns FLUX, MAG and KCOR
c
c [modified from PEAKMAG_CALC]
c
c
c Mar 24, 2008: add 'REST2' option to get rest-mag
c               from cosmology instead of from model.
c
c April 6, 2008: add new return arguments FLUXERR and MAGERR,
c                which are computed using full covariance matrix.
c
c Dec 18, 2011: for photoZ fit, return if min or max filter-lambda
c               is outside model-wavelength range => avoids abort.
c
c ----------------------------------------------
      IMPLICIT NONE

      INTEGER
     &   ifilt  ! (I) IFILT_OBS or IFILT_REST (depends on CFRAME)

      CHARACTER CFRAME*(*)  ! (I) 'REST' or 'OBS' or 'REST2'

      REAL*8
     &   MJD
     &  ,FLUX, FLUXERR
     &  ,MAG,  MAGERR
     &  ,KCOR


c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.cars inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      REAL*8
     &   TREF, MAGOFF, TOBS, MAGOFF_REST
     &  ,SQSIG_FLUX, PKMJD, LAMMIN, LAMMAX, Z1, Z

      INTEGER OPT, OPT_KCOR, ipar1, ipar2, i, NLAM, LL
      LOGICAL LOBS, LREST, LDMP

      CHARACTER CFILT1, CFRAME_LOC*8

c functions
      REAL*8  GET_FLUX_FITFUN, COVFLUXFUN

C ----------------- BEGIN --------------

c init output args
      MAG     =  99.
      MAGERR  = -9.0
      FLUX    = -9.0
      FLUXERR = -9.0

      cfilt1     = filtdef_string(ifilt:ifilt)

      CFRAME_LOC = CFRAME

      LOBS  = .FALSE.
      LREST = .FALSE.

      PKMJD = LCVAL_STORE(IPAR_PEAKMJD) + MJDOFF
      TOBS  =  MJD - PKMJD

      IF ( PARNAME_STORE(IPAR_DLMAG) .EQ. 'DLMAG' ) THEN
         MAGOFF_REST = -PEAKMAG_AT_10pc
      ELSE
         MAGOFF_REST = 0.0
      ENDIF

      IF ( CFRAME_LOC(1:3) .EQ. 'OBS' ) THEN
          LOBS   = .TRUE.
          OPT    = 0
          MAGOFF = 0.0
          TREF   = TOBS

      ELSE IF ( CFRAME_LOC(1:5) .EQ. 'REST2' ) THEN
          LOBS   = .TRUE.
          OPT    = 3  ! 2=> includes AV; 3 => subtract XTAV
          MAGOFF = MAGOFF_REST
          TREF   =  TOBS

      ELSE IF ( CFRAME_LOC(1:4) .EQ. 'REST' ) THEN
          LREST  = .TRUE.
          OPT    = 1
          MAGOFF = MAGOFF_REST
          TREF   = TOBS / ( 1. + REDSHIFT_FIT )
      ELSE
         c1err = 'Unknown CFRAME = ' // CFRAME
         write(c2err,660) SNLC_CCID, IFILT
660      format('CID=',A8, 4x, 'IFILT=', I2 )
         CALL MADABORT("MODELMAG_CALC", c1err, c2err )
      ENDIF

      LDMP =  ( LREST .and. IFILT .EQ. -IFILT_BESS_B )
c ---------------------
c get the flux

      Flux  =  GET_FLUX_FITFUN ( ifilt, TREF, OPT )

      SQSIG_FLUX =
     &   COVFLUXFUN(OPT, ifilt, ifilt, TREF, TREF, LDMP )

c -------
c      print*,' OLD/NEW= ', SNGL(SQSIG_FLUX/U12),
c     &   '  COV=',U12, '  at TREF=',sngl(TREF),'  ifilt=',ifilt
c ------

      if ( SQSIG_FLUX < 0.0 ) then
         write(c1err,661) CFILT1, SQSIG_FLUX, SNLC_CCID
661      format('SQSIG_FLUX(',A,')=', G10.4,' for CID=',A )
         c2err = ' '
         print*,' MODELMAG_CALC WARNING: ', c1err(1:50)
cc         CALL MADABORT("MODELMAG_CALC", c1err, c2err )
      endif

      Fluxerr = sqrt ( abs(SQSIG_FLUX) )


c convert flux to MAG.

      if ( Flux .GT. 1.0E-20 ) then
        mag    = -2.5 * LOG10(Flux) + MAGOFF + ZEROPOINT_FLUXCAL_DEFAULT
        magerr =  2.5 * LOG10(1.0 + Fluxerr/Flux)
      else
        mag    = 99.
        magerr = 9.
      endif

c get the K-correction
      if ( LOBS .and. LKCOR_AVWARP ) THEN
        OPT_KCOR = 10
        KCOR  = GET_FLUX_FITFUN (  ifilt, TREF, OPT_KCOR )
      else
        KCOR = 0.0
      endif

c+SELF,IF=XXXDBG.
c xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
      if ( LDMP ) THEN
         print*,' xxx Peak FLUX = ', SNGL(Flux/1.0E18),
     &       ' +- ', SNGL(fluxerr/1.0E18)
         print*,' xxx Peak MAG = ', mag,' +- ' , magerr
         print*,' xxx ---------------------------- '
         call flush(6)          ! xxxxxx
      ENDIF
c xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
c+SELF.

      RETURN
      END   ! end of MODELMAG_CALC

C ======================================
CDECK  ID>,  PEAKMAG_CALC. 
      SUBROUTINE PEAKMAG_CALC ( IFILTDEF, CFRAME )
c
c Created Jan, 2008
c Just calls MODELMAG_CALC with PKMJD = PEAKMJD
c
c Feb 20 2017: convert input IFILTDEF to sparse index IFILT,
c              and fill arrays with sparse IFILT.
c
c ----------------------------------------------
      IMPLICIT NONE

      INTEGER
     &   ifiltdef  ! (I) IFILT_OBS or IFILT_REST (depends on CFRAME)

      CHARACTER CFRAME*(*)  ! (I) 'REST' or 'OBS'

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFILT
      REAL*8 PKMJD, FLUX, FLUXERR, MAG, MAGERR, KCOR

C ----------------- BEGIN --------------

      PKMJD = LCVAL_STORE(IPAR_PEAKMJD) + MJDOFF

      CALL MODELMAG_CALC(IFILTDEF,CFRAME, PKMJD,   ! (I) inputs
     &     FLUX, FLUXERR, MAG, MAGERR, KCOR)    ! (O) return args

      if ( CFRAME(1:3) .EQ. 'OBS' ) THEN
        IFILT = IFILTDEF_INVMAP_SURVEY(ifiltdef) ! get sparse index

        PEAKMAG_OBS_MODEL(ifilt)     = MAG
        PEAKMAG_OBS_MODEL_ERR(ifilt) = MAGERR

        PEAKFLUX_OBS_MODEL(ifilt)     = FLUX
        PEAKFLUX_OBS_MODEL_ERR(ifilt) = FLUXERR

        PEAK_KCOR_MODEL(ifiltdef)        = KCOR
      ELSE
        PEAKMAG_REST_MODEL(ifiltdef)     = MAG
        PEAKMAG_REST_MODEL_ERR(ifiltdef) = MAGERR
      ENDIF

      RETURN
      END  ! end PEAKMAG_CALC

C =====================================
CDECK  ID>,  COVFLUXFUN. 
      REAL*8 FUNCTION COVFLUXFUN(OPT, ifilt1,ifilt2, T1,T2,LDMP )

c
c Created April 6, 2008 by R.Kessler
c
c Get the model-Flux covariance between any two epochs/filters
c using full fitpar covariance, FITERRMAT(ipar1,ipar2)
c  ( see eq. 32.24 in PDG statistics section)
c
c COVFLUXFUN = U12,
c
c                           dF1   dF2
c U12       = \sum_{k,l}  ------ ------ * FITERRMAT(k,l)
c                         dPAR_k dPAR_l
c
c  where PAR_k = fit-parameter with index 'k'.
c  and F1,F2 are fluxes at days with index 1,2.
c
c If ifilt1=ifilt2 and T1=T2,  then U12 = square of model
c uncertainty at this epoch.
c
c Mar 26 2014: add new LDMP argument
c
c -------------------------------

      IMPLICIT NONE

c subroutine args:

      INTEGER
     &   OPT     ! (I) option for GET_FLUX_FITFUN
     &  ,IFILT1  ! (I) ifilt_obs or ifilt_rest (depends on OPT)
     &  ,IFILT2  ! (I) idem for other epoch

      REAL*8  T1, T2  ! (I) epoch (days) to get covariance

      LOGICAL LDMP  ! (I) dump flag.

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER
     &   ipar_k, ipar_l

      REAL*8
     &   FLUX1, FLUX2
     &  ,FTMP1, FTMP2
     &  ,SAVEVAL_k, SAVEVAL_l
     &  ,ERRPAR_k,  ERRPAR_l
     &  ,dF1dVAL_k, dF2dVAL_l, FF
     &  ,V_kl, U12

c functions
      REAL*8  GET_FLUX_FITFUN

C -------------- BEGIN -------------

      COVFLUXFUN = 0.0
      U12 = 0.0   ! init output

c get reference fluxes to computer deriviates below.

      Flux1   =  GET_FLUX_FITFUN ( ifilt1, T1, OPT )
      Flux2   =  GET_FLUX_FITFUN ( ifilt2, T2, OPT )

      DO 301 ipar_k = 1, NFITPAR_MN
         if ( .NOT. FLOATPAR(ipar_k) ) goto 301
      DO 302 ipar_l = 1, NFITPAR_MN
         if ( .NOT. FLOATPAR(ipar_l) ) goto 302

         SAVEVAL_k = LCVAL_STORE(ipar_k)
         SAVEVAL_l = LCVAL_STORE(ipar_l)

         ERRPAR_k  = LCERR_STORE(ipar_k)
         ERRPAR_l  = LCERR_STORE(ipar_l)

c change fitpar values by +1 sigma and re-evaluate Flux.

         LCVAL_STORE(ipar_k) =
     &   LCVAL_STORE(ipar_k) + SNGL(ERRPAR_k)
         Ftmp1   =  GET_FLUX_FITFUN ( ifilt1, T1, OPT )
         LCVAL_STORE(ipar_k) = SNGL(SAVEVAL_k)

c repeat for 2nd fitpar ...
         LCVAL_STORE(ipar_l) =
     &   LCVAL_STORE(ipar_l) + SNGL(ERRPAR_l)
         Ftmp2   =  GET_FLUX_FITFUN ( ifilt2, T2, OPT )
         LCVAL_STORE(ipar_l) = SNGL(SAVEVAL_l)

c make sure that errors are non-zero before dividing.

         c2err = ' '
         if ( ERRPAR_k .EQ. 0.0 ) then
           write(c1err,662) PARNAME_STORE(ipar_k)
           CALL MADABORT("COVFLUXFUN", c1err, c2err )
         endif
         if ( ERRPAR_l .EQ. 0.0 ) then
           write(c1err,662) PARNAME_STORE(ipar_l)
           CALL MADABORT("COVFLUXFUN", c1err, c2err )
         endif
662      format('Cannot compute FLUXERR with ERR(',A,') = 0' )

c evaluate partial deriviates for flux
         dF1dVAL_k = (Ftmp1 - Flux1) / ERRPAR_k
         dF2dVAL_l = (Ftmp2 - Flux2) / ERRPAR_l

         FF   = dF1dVAL_k * dF2dVAL_l
         V_kl = FITERRMAT(ipar_k,ipar_l)
         U12  = U12 + FF * V_kl

         if ( LDMP .and. FF .NE. 0.0 ) then
            print*,' xxx COVFLUXFUN DUMP for ',
     &          parname_store(ipar_k)(1:10),
     &          parname_store(ipar_l)(1:10)
            print*,' xxx   FF, V_kl, U12 ',
     &           sngl(FF/1.0E35), sngl(V_kl), sngl(U12/1.0E35)
            print*,' xxx   dF1,dF2 = ',
     &          sngl(dF1dVAL_k/1.0E18), sngl(dF2dVAL_l/1.0E18)
            print*,' xxx   ERR1,ERR2 = ',
     &          sngl(ERRPAR_k), sngl(ERRPAR_l)
            call flush(6)
         endif

302   CONTINUE
301   CONTINUE

      COVFLUXFUN = U12

      RETURN
      END

C ======================================
CDECK  ID>,  COVFUDGE. 
      DOUBLE PRECISION FUNCTION COVFUDGE_DATA( irow, icol )
c
c Created Feb 23 2015 by R.Kessler
c Compute fudged data-covariance from &SNLCINP  namelist
c input FUDGE_MAG_COVERR.
c
      IMPLICIT NONE

      INTEGER irow, icol   ! (I) matrix location

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      REAL*8 COV, R1, R2, ERR1, ERR2, F1, F2
      INTEGER IFILT1, IFILT2

C -------------- BEGIN --------------

      COVFUDGE_DATA = 0.0
      if ( FUDGE_MAG_COVERR .EQ. ' ' ) RETURN  ! no fudge requested

      ifilt1  = I4EP_ALL(irow,IEP_IFILT_OBS)
      ifilt2  = I4EP_ALL(icol,IEP_IFILT_OBS)

      if ( ifilt1 .NE. ifilt2 ) RETURN  ! no cov for different filters.

      R1   = FUDGE_MAG_COVERR_FILT(ifilt1)  ! mag error
      R1   = 1.0 - 10.0**(-0.4*R1)          ! exact sigF/F
      R2   = R1
      F1   = R4EP_ALL(irow,JEP_DATAFLUX)    ! flux
      F2   = R4EP_ALL(icol,JEP_DATAFLUX)
      ERR1 = F1 * R1                       ! error on flux
      ERR2 = F2 * R2

      COVFUDGE_DATA  = (ERR1 * ERR2)

      RETURN
      END   ! end of COVFUDGE_DATA


C =====================================
CDECK  ID>,  RHOFUDGE. 
      DOUBLE PRECISION FUNCTION RHOFUDGE_MODEL( irow, icol, RHO )

c Created Sep 20, 2006
c
c Return fudged correlation coefficients for systematic studies
c on model errors.
c Fudge only non-zero elements using FUDGE_COVAR as explained below.
c
      IMPLICIT NONE


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER irow, icol   ! (I) matrix location
      REAL*8  RHO          ! (I) un-fudged rho = COV[1,2]/sig1*sig2
      LOGICAL LPRINT       ! (I) print comment
c local var

      REAL*8 RHOSGN, RHOABS, RHOTMP
      LOGICAL LDMP  ! print fudge formula if TRUE

C --------- BEGIN ---------

      RHOFUDGE_MODEL = RHO  ! default is no fudge

c check option to print fudge-formual

      LDMP = ( irow .LE. 0 .and. irow .LE. 0 )
      IF ( LDMP ) THEN

cc         CALL PRBANNER("RHOFUDGE: FUDGE RHO = COV[i,j]/sig_i*sig_j")

         IF ( FUDGE_COVAR .EQ. 0.0 ) THEN
cc            print*,'      No fudge for RHO '
         ELSE IF ( FUDGE_COVAR .LT. 0.0 ) THEN
            write(6,21) abs(FUDGE_COVAR)
21          format(T10,'FUDGE non-zero |RHO| -> ',
     &                 '|RHO| x [ 1 - ',F5.2,' ]' )
         ELSE IF ( FUDGE_COVAR .GT. 0.0 ) THEN
            write(6,22) FUDGE_COVAR
22          format(T10,'FUDGE non-zero |RHO| -> ',
     &                   '|RHO| + [ 1 - |RHO| ] x ',F5.2 )
         ENDIF
         RETURN
      ENDIF

c ------------------------------------
c do NOT fudge ...

      if ( irow  .EQ. icol ) return  ! skip diagonal elements
      if ( RHO   .EQ. 0.0  ) return  ! elements already = 0

c bail if fudge is not requested
      if ( FUDGE_COVAR .EQ. 0.0  ) return

c ------------------------
444   CONTINUE

      RHOABS = ABS(RHO)
      RHOSGN = RHO / ABS(RHO)

c as FUDGE_COVAR spans -1 to 1, |RHO| spans 0 to 1
c Positive FUDGE_COVAR increases |RHO| up to 1.0 ;
c Negative FUDGE_COVAR decreases |RHO| down to zero.

      IF ( FUDGE_COVAR .LT. 0.0 ) THEN
         RHOTMP = RHOABS * (1.0 + FUDGE_COVAR)
      ELSE IF ( FUDGE_COVAR .GT. 0.0 ) THEN
         RHOTMP = RHOABS + (1.0 - RHOABS) * FUDGE_COVAR
      ENDIF

      RHOFUDGE_MODEL = RHOTMP * RHOSGN

c  make sure that |RHOFUDGE| < 1 to avoid singular matrix.

      IF ( RHOFUDGE_MODEL .GE.  1.00000 ) THEN
          RHOFUDGE_MODEL =  +1.0 - 1.0E-08
      ENDIF

      IF ( RHOFUDGE_MODEL .LE. -1.00000 ) THEN
         RHOFUDGE_MODEL =  -1.0 + 1.0E-08
      ENDIF

      RETURN
      END   ! end of RHOFUDGE_MODEL

C ==================================================
CDECK  ID>,  VMAX_INI. 
      SUBROUTINE VMAX_INI

c Created Jun 2013 by R.Kessler
c
c Initialization for 1/Vmax method.
c Parse user inputs  MAGLIM_VMAX and OPT_VMAX
c

      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )



C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,VMAXCOM. inserted below by ypatchy. 

c Created Jun 2013 by R.K.

c Examples for OPT_VMAX
c  OPT_VMAX = 2 -> use obs for mag, peak for Zmax
c  OPT_VMAX = 3 -> use peak for both mag and Zmax


      INTEGER
     &  MXFILT_VMAX
     & ,OPTBIT_MAG    ! Zmax at epoch of max obs brightness
     & ,OPTBIT_ZMAX
     & ,OPTBIT_VERBOSE

      REAL*8  MAGDIF_CONVERGE

      PARAMETER (
     &   MXFILT_VMAX   = 5
     &  ,OPTBIT_MAG    = 0  ! bit0 off/on -> mag at best-fit obs/peak
     &  ,OPTBIT_ZMAX   = 1  ! bit1 off/on -> zmax from best-fot obs/peak
     &  ,OPTBIT_VERBOSE = 7 ! bit7(128) -> verbose printout
     &  ,MAGDIF_CONVERGE = 0.001 ! stop when |mag(zmax)-MAGLIM| < CONVERGE
     &     )

      INTEGER
     &   NFILT_VMAX   !Number of obs filters to compute Zmax/Vmax
     &  ,IFILTOBS_LIST_VMAX(MXFILT_VMAX) ! sparse list

      REAL
     &   MAGLIM_LIST_VMAX(MXFILT_VMAX)
     &  ,TREST_LIST_VMAX(MXFILT_VMAX)
     &  ,MAG_LIST_VMAX(MXFILT_VMAX)
     &  ,Z_LIST_VMAX(MXFILT_VMAX)
     &  ,VOL_LIST_VMAX(MXFILT_VMAX)

      INTEGER NEP_LIST_VMAX(MXFILT_VMAX)

      CHARACTER FILTLIST_VMAX*20

      COMMON/ VMAXCOM /
     &    NFILT_VMAX, IFILTOBS_LIST_VMAX
     &   ,FILTLIST_VMAX, MAGLIM_LIST_VMAX
     &   ,TREST_LIST_VMAX, MAG_LIST_VMAX, Z_LIST_VMAX, VOL_LIST_VMAX
     &   ,NEP_LIST_VMAX

C ===================================

c +CDE,SNLCINP.
c +CDE,SNANAFIT.
c +CDE,SNFITCOM.
c +CDE,FILTCOM.

      INTEGER IFILT, IFILT_OBS, NFTMP, IFLIST(MXFILT_OBS)
      REAL    MAGLIM,  MAGLIST(MXFILT_OBS)
      CHARACTER FNAM*12, CFILT*2

C ------------- BEGIN -------------

      NFILT_VMAX = 0
      IF ( MAGLIM_VMAX .EQ. ' ' ) RETURN

      FNAM = "VMAX_INI"
      CALL PRBANNER('VMAX_INI: Initialize Zmax for 1/Vmax method')

      IF ( BTEST(OPT_VMAX,OPTBIT_MAG) )  THEN
        write(6,42) 'Compute best-fit MAG at epoch of peak brightness.'
      ELSE
        write(6,42) 'Compute best-fit MAG at epoch of max flux.'
      ENDIF

      IF ( BTEST(OPT_VMAX,OPTBIT_ZMAX) )  THEN
        write(6,42) 'Compute Zmax at epoch of peak brightness.'
      ELSE
        write(6,42) 'Compute Zmax at epoch of max flux.'
      ENDIF

      IF ( BTEST(OPT_VMAX,OPTBIT_VERBOSE) )  THEN
         write(6,42) 'Verbose mode ON.'
      ENDIF

 42   format(T8,'VMAX: ', A)

      CALL FLUSH(6)

c ---------------------------------
c translate user string MAGLIM_VMAX

      CALL PARSE_FILTSTRING(1, MAGLIM_VMAX,          ! inputs
     &    NFILT_VMAX, IFLIST, MAGLIST )  ! return args

      IF ( NFILT_VMAX > MXFILT_VMAX ) THEN
         write(c1err,671) NFILT_VMAX, MXFILT_VMAX
 671     format('NFILT_VMAX = ', I2,' exceeds bound of MXFILT_VMAX=',I2)
         c2err = 'Reduce NFILT_VMAX or increase MXFILT_VMAX.'
         CALL MADABORT(FNAM, c1err, c2err )
      ENDIF

      FILTLIST_VMAX = ''

      DO 20 IFILT = 1, NFILT_VMAX

         IFILTOBS_LIST_VMAX(IFILT) = IFLIST(IFILT)
         MAGLIM_LIST_VMAX(IFILT)   = MAGLIST(IFILT)

         IFILT_OBS = IFILTOBS_LIST_VMAX(ifilt)
         MAGLIM    = MAGLIM_LIST_VMAX(ifilt)
         CFILT     = FILTDEF_STRING(IFILT_OBS:IFILT_OBS)
         write(6,21) CFILT, MAGLIM, IFILT_OBS
 21      format(T12,'MAGLIM(',A1,') = ', F5.2, 3x,'(IFILTOBS=',I3,')' )

         NFTMP = INDEX(FILTLIST_VMAX,' ') - 1
         FILTLIST_VMAX = FILTLIST_VMAX(1:NFTMP) // CFILT(1:1)
 20   CONTINUE

      CALL FLUSH(6)

      RETURN
      END      ! end of VMAX_INI

C ==================================================
CDECK  ID>,  DMPVMAX. 
      SUBROUTINE DMPVMAX(CCID,CFILT,NITER,ZMAX,MAGDIF,MAG)

C utility to dump one line for VERBOSE option
      IMPLICIT NONE

      CHARACTER CCID*(*)
      CHARACTER CFILT*(*)   ! (I)
      INTEGER NITER         ! (I)
      REAL*8  ZMAX, MAGDIF,MAG  ! (I)

c locals
      REAL*8  MMAG
      INTEGER LCCID

C ---------- BEGIN ----------

      LCCID = INDEX(CCID,' ') - 1
      MMAG  = 1000. * MAGDIF

      write(6,505) CCID(1:LCCID),CFILT, NITER, zmax, MMAG, MAG
 505  format(T5,A,'-',A, ' :  Zmax(ITER=',I2,')=', F6.4,3x,
     &     'MAGDIF=',F7.2,' mmag', 2x,'MAG=',F7.3 )
      CALL FLUSH(6)

      RETURN
      END

C ==================================================
CDECK  ID>,  VMAX_ANA. 
      SUBROUTINE VMAX_ANA(IFILT_VMAX)

c Created Jun 2013 by R.Kessler
c
c Compute Zmax/Vmax for 1/Vmax method.
c
c Jun 28 2013:
c  Fix bug setting x0 = LCVAL_STORE(IPAR_DLMAG)  in iterative loop.
c
      IMPLICIT NONE

      INTEGER IFILT_VMAX  ! (I) sparse filter index for VMAX calc



C +CDE,SNDATCOM.   from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,VMAXCOM. inserted below by ypatchy. 

c Created Jun 2013 by R.K.

c Examples for OPT_VMAX
c  OPT_VMAX = 2 -> use obs for mag, peak for Zmax
c  OPT_VMAX = 3 -> use peak for both mag and Zmax


      INTEGER
     &  MXFILT_VMAX
     & ,OPTBIT_MAG    ! Zmax at epoch of max obs brightness
     & ,OPTBIT_ZMAX
     & ,OPTBIT_VERBOSE

      REAL*8  MAGDIF_CONVERGE

      PARAMETER (
     &   MXFILT_VMAX   = 5
     &  ,OPTBIT_MAG    = 0  ! bit0 off/on -> mag at best-fit obs/peak
     &  ,OPTBIT_ZMAX   = 1  ! bit1 off/on -> zmax from best-fot obs/peak
     &  ,OPTBIT_VERBOSE = 7 ! bit7(128) -> verbose printout
     &  ,MAGDIF_CONVERGE = 0.001 ! stop when |mag(zmax)-MAGLIM| < CONVERGE
     &     )

      INTEGER
     &   NFILT_VMAX   !Number of obs filters to compute Zmax/Vmax
     &  ,IFILTOBS_LIST_VMAX(MXFILT_VMAX) ! sparse list

      REAL
     &   MAGLIM_LIST_VMAX(MXFILT_VMAX)
     &  ,TREST_LIST_VMAX(MXFILT_VMAX)
     &  ,MAG_LIST_VMAX(MXFILT_VMAX)
     &  ,Z_LIST_VMAX(MXFILT_VMAX)
     &  ,VOL_LIST_VMAX(MXFILT_VMAX)

      INTEGER NEP_LIST_VMAX(MXFILT_VMAX)

      CHARACTER FILTLIST_VMAX*20

      COMMON/ VMAXCOM /
     &    NFILT_VMAX, IFILTOBS_LIST_VMAX
     &   ,FILTLIST_VMAX, MAGLIM_LIST_VMAX
     &   ,TREST_LIST_VMAX, MAG_LIST_VMAX, Z_LIST_VMAX, VOL_LIST_VMAX
     &   ,NEP_LIST_VMAX

C ===================================

C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


c +CDE,SNLCINP.

      INTEGER JOBS, JFIT
      PARAMETER ( JOBS=1, JFIT=2 )

      INTEGER  IFITDATA, IFILT, IFILT_OBS, IMJD, j, ep
      INTEGER  NITER, OPTWGT, NEP

      CHARACTER CFILT*1
      LOGICAL LVBOSE

      REAL*8
     &   PEAKMJD, MJD, FLUXCAL(2), MAGTMP(2), Tobs, Trest
     &  ,FLUXCAL_atmax(2), Trest_atmax(2), mag_atmax(2)
     &  ,FLUXCAL_TMP, FLUXCAL_ERR, MAG_ERR, KCOR
     &  ,MAGDIF, MAG, MAGLIM, zmax, Vmax, COSPAR(10)
     &  ,z_save, d_save, shape, color, d0, d

c function
      REAL*8 GET_DIST8, DVDZ_INTEGRAL

C ------------- BEGIN -------------

c init all global output to crazy values.
      MAG_LIST_VMAX(ifilt_Vmax)   =  99.
      TREST_LIST_VMAX(ifilt_Vmax) =  99.
      Z_LIST_VMAX(ifilt_Vmax)     = -99.
      VOL_LIST_VMAX(ifilt_Vmax)   = -99.
      NEP_LIST_VMAX(ifilt_Vmax)   =  0

      IF ( NFILT_VMAX .EQ. 0 ) RETURN

      LVBOSE = BTEST(OPT_VMAX,OPTBIT_VERBOSE)

c strip off a few globals into local variables
      IFILT_OBS = IFILTOBS_LIST_VMAX(ifilt_Vmax)
      MAGLIM    = MAGLIM_LIST_VMAX(ifilt_Vmax)
      PEAKMJD   = LCVAL_STORE(IPAR_PEAKMJD)
      CFILT     = FILTDEF_STRING(IFILT_OBS:IFILT_OBS)

c find brightest epoch, both observed and best-fit.
      DO j = 1, 2
         FLUXCAL_atmax(j) = -9.9E+8  ! must be negative for logic below
         Trest_atmax(j)   =  99.
         mag_atmax(j)     =  99.
      ENDDO
      NEP     = 0

      DO 200 ifitdata = 1, NFITDATA

         ep = EPLIST_FIT(ifitdata)

         if ( ifilt_obs .NE. I4EP_ALL(ep,IEP_IFILT_OBS) ) GOTO 200

c         ifilt     = I4EP_IFILT(ifitdata)  ! sparse fit index, not Vmax
c         imjd      = I4EP_IMJD(ifitdata)

         MJD     = R4EP_ALL(ep,JEP_MJD)
         Tobs    = MJD - PEAKMJD
         Trest   = Tobs / (1. + SNLC_REDSHIFT)

c extract observed flux and mag just in case;
c we should not need this.
          FLUXCAL(JOBS)      = R4EP_ALL(ep,JEP_DATAFLUX)
          MAGTMP(JOBS)       = R4EP_ALL(ep,JEP_DATAMAG)

c idem for best-fit flux and mag; use this
          FLUXCAL(JFIT)      = R4EP_ALL(ep,JEP_MODELFLUX)
          MAGTMP(JFIT)       = R4EP_ALL(ep,JEP_MODELMAG)

c keep track of max FLUXCALs
          DO j = 1, 2
             if ( FLUXCAL(j) > FLUXCAL_atmax(j) ) then
                FLUXCAL_atmax(j) = FLUXCAL(j)
                mag_atmax(j)     = MAGTMP(j)
                Trest_atmax(j)   = Trest
             endif
          ENDDO

          NEP = NEP + 1

200   CONTINUE   ! ifitdata


c --- load common block variables -------

      NEP_LIST_VMAX(ifilt_Vmax) = NEP

      IF ( BTEST(OPT_VMAX,OPTBIT_MAG) ) THEN
        MAG_LIST_VMAX(ifilt_Vmax)   = PEAKMAG_OBS_MODEL(IFILT_Vmax)
        TREST_LIST_VMAX(ifilt_Vmax) = 0.0
      ELSE
        MAG_LIST_VMAX(ifilt_Vmax)   = MAG_atmax(JFIT)
        TREST_LIST_VMAX(ifilt_Vmax) = Trest_atmax(JFIT)
      ENDIF


c bail if we have an undefined MAG to work with
      if ( abs(MAG_LIST_VMAX(ifilt_Vmax)) > 98.0 ) RETURN

      Trest    = TREST_LIST_VMAX(ifilt_Vmax)
      Tobs     = TREST*(1.0 + SNLC_REDSHIFT)
      MJD      = MJDOFF + PEAKMJD + Tobs

c save fit quantities that need to be changed to find zmax
      z_save = LCVAL_STORE(IPAR_zPHOT)
      d_save = LCVAL_STORE(IPAR_DLMAG)  ! DLMAG or x0

c need color and shape parameter for distance(zmax) calc.
      SHAPE = LCVAL_STORE(IPAR_SHAPE)
      COLOR = LCVAL_STORE(IPAR_COLOR)

      NITER  = 0
      zmax   = SNLC_REDSHIFT  ! initial guess is current redshift
      d0     = GET_DIST8(zmax,SHAPE,COLOR,ONE8)  ! reference x0/mu

c first MAG-DIF for iterative loop
      MAG    = MAG_LIST_VMAX(ifilt_Vmax)
      MAGDIF = MAGLIM - MAG

      IF ( LVBOSE  ) THEN
         print*,' '
         print*,' ########## 1/Vmax DUMP ############# '

         print*,'    MAG   = ', MAG_LIST_VMAX(ifilt_Vmax),
     &           '      MAGLIM,MAGDIF=', sngl(MAGLIM), sngl(MAGDIF)
         print*,'    Trest = ', TREST_LIST_VMAX(ifilt_Vmax)
         print*,'    d,c,s = ', sngl(d_save), sngl(color), sngl(shape)

         CALL DMPVMAX(SNLC_CCID,CFILT,NITER,ZMAX,MAGDIF,MAG)
      ENDIF
c ----------------------------------------
      DO 300 WHILE ( abs(MAGDIF) > MAGDIF_CONVERGE )

c modify zmax and distance before re-computing model mag at zmax;
c for each iteration,
c (zmax/z)^2  = FLux(z)/FLUXLIM = 10**[0.4*(MAGLIM - mag(z))]
         zmax = zmax * 10.0**(0.2*(MAGDIF))
         d    = GET_DIST8(zmax,SHAPE,COLOR,ONE8) ! compute dist: x0 or mu

         LCVAL_STORE(IPAR_zPHOT) = zmax

         IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
            LCVAL_STORE(IPAR_DLMAG)  = d_save * d/d0  ! scale x0
         ELSE
            LCVAL_STORE(IPAR_DLMAG)  = d_save + (d0-d) ! MU-dif -> UNTESTED!
         ENDIF

         CALL MODELMAG_CALC(IFILT_OBS, 'OBS', MJD,
     &        FLUXCAL_TMP, FLUXCAL_ERR, MAG, MAG_ERR, KCOR)

         MAGDIF = MAGLIM - MAG
         NITER  = NITER + 1

         IF ( LVBOSE  ) THEN
            CALL DMPVMAX(SNLC_CCID,CFILT,NITER,ZMAX,MAGDIF,MAG)
cc            print*,'          x0 = ' , LCVAL_STORE(IPAR_DLMAG)
         ENDIF

         if ( NITER > 20 ) THEN
            print*,' '
            print*,' xxx ------------------------- '
            print*,' xxx IFILT_OBS,VMAX = ', IFILT_OBS, IFILT_VMAX
            print*,' xxx MAG_atmax  = ', MAG_atmax
            print*,' xxx MJD, Tobs  = ', MJD, Tobs
            print*,' xxx PEAKMAG    = ', PEAKMAG_OBS_MODEL(IFILT_VMAX)
            print*,' xxx PEAKMJD    = ', PEAKMJD
            print*,' xxx NEPOCH     = ', NEP
            print*,' xxx zmax, mag = ', sngl(zmax), sngl(mag), NITER
            call flush(6)

            write(c1err,661) NITER
 661        format('Too many zmax iterations: NITER = ',I3 )
            c2err = 'for CID = ' // SNLC_CCID
            CALL MADABORT("VMAX_ANA", c1err, c2err )
         endif

 300  CONTINUE

c ------------------------------
c compute volume out to zmax

      OPTWGT    = 0  ! do NOT weight by redshift
      COSPAR(1) = H0_REF(1)
      COSPAR(2) = OMAT_REF(1)
      COSPAR(3) = OLAM_REF(1)
      COSPAR(4) = W0_REF(1)
      COSPAR(5) = 0.0        ! wa
      Vmax   = 4.0 * PI * DVDZ_INTEGRAL(OPTWGT, zmax, COSPAR )

c -----------
c store results in globals
      Z_LIST_VMAX(ifilt_Vmax)     = zmax
      VOL_LIST_VMAX(ifilt_Vmax)   = Vmax

c restore LCVAL_STORE values
      LCVAL_STORE(IPAR_zPHOT) = z_save
      LCVAL_STORE(IPAR_DLMAG)  = d_save

      RETURN
      END        ! end of VMAX_ANA


C ================================================
CDECK  ID>,  MAGDIFINI. 
      SUBROUTINE FITMAGDIF_INI
c
c Created Mar 2013
c Prepare fits for 1-filter only, all other filters,
c and all filters.

      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,MAGDIFCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c Mar 2013: for FILTER_FITMAGDIF option

      INTEGER
     &   NFIT_ITER_FITMAGDIF
     &  ,IFLAG_FITMAGDIF_NOMINAL
     &  ,IFLAG_FITMAGDIF_1FILT  ! fit only test filter
     &  ,IFLAG_FITMAGDIF_XFILT  ! exclude test filter
     &  ,IFILTOBS_FITMAGDIF     ! absolute index
     &  ,IFILT_FITMAGDIF        ! sparse survey-filter index

      PARAMETER (
     &   NFIT_ITER_FITMAGDIF     = 1    ! Number of fit-iters per test
     &  ,IFLAG_FITMAGDIF_NOMINAL = 0
     &  ,IFLAG_FITMAGDIF_1FILT   = 1
     &  ,IFLAG_FITMAGDIF_XFILT   = 2
     &      )

      INTEGER
     &   IFLAG_FITMAGDIF(MXITER)  ! 1-> one filter fit, 2-> complement
     &  ,NFILT_FITMAGDIF(MXITER)  ! NFILT to fit per iteration

      CHARACTER
     &   FILTLIST_FITMAGDIF(MXITER)*(MXFILT_ALL) ! filter-list per iteration

      REAL
     &   FITMAG_1FILT, FITMAGERR_1FILT
     &  ,FITMAG_XFILT, FITMAGERR_XFILT
     &  ,FITMAGDIF, FITERRDIF
     &  ,FITPROB_1FILT, FITPROB_XFILT

      COMMON / MAGDIFCOM / IFLAG_FITMAGDIF, NFILT_FITMAGDIF
     &    ,IFILTOBS_FITMAGDIF, IFILT_FITMAGDIF
     &    ,FILTLIST_FITMAGDIF
     &    ,FITMAG_1FILT, FITMAGERR_1FILT
     &    ,FITMAG_XFILT, FITMAGERR_XFILT
     &    ,FITMAGDIF, FITERRDIF
     &    ,FITPROB_1FILT, FITPROB_XFILT


      LOGICAL    L0, L1, L2, LX
      INTEGER
     &   iter, IFLAG, NFILT, NFILT_ALL
     &  ,IFILTDEF, IFILT, NFIT_PER_SN

      CHARACTER  FILTLIST*(MXFILT_ALL), CFILT*2, CTMP*28

c function
      INTEGER FILTINDX

C ------------------ BEGIN -----------

      IF ( FILTER_FITMAGDIF .EQ. '' ) RETURN

      global_banner = 'FITMAGDIF_INI: prepare 2 fit methods for mag-'
     &            // FILTER_FITMAGDIF

      CALL PRBANNER ( GLOBAL_BANNER(1:60) )

      NFIT_PER_SN = 3
      CALL SNLCPAK_NFIT_PER_SN(NFIT_PER_SN)   ! see sntools_output.c

c get filter index (absolute and sparse) for test filter.
      IFILTDEF  = FILTINDX(FILTER_FITMAGDIF)
      IFILT     = IFILTDEF_INVMAP_SURVEY(IFILTDEF)
      IFILTOBS_FITMAGDIF = IFILTDEF
      IFILT_FITMAGDIF    = IFILT

      IF ( IFILT < 0 ) THEN
        c1err = 'Invalid FILTER_FITMAGDIF = ' // FILTER_FITMAGDIF
        c2err = 'Must use valid SURVEY filter: ' //
     &       SURVEY_FILTERS(1:NFILTDEF_SURVEY)
        CALL MADABORT('FITMAGDIF_INI', c1err, c2err)
      ENDIF

c --------
      NFIT_ITERATION_ALLFILT = NFIT_ITERATION
      NFIT_ITERATION  =
     &    NFIT_ITERATION_ALLFILT   ! nominal, fix t0,c,shape
     &  + 2*NFIT_ITER_FITMAGDIF    ! special fits
     &  + 1                        ! nominal again

      NFILT_ALL = INDEX(FILTLIST_FIT,' ') - 1
      DO 100 iter = 1, NFIT_ITERATION

            IFLAG    = -9
            NFILT    = -9
            FILTLIST = '???'
            CTMP = ' '

        L0 =     ( iter .LE. NFIT_ITERATION_ALLFILT )
     &     .or.  ( iter .EQ. NFIT_ITERATION )

        L1 = (iter .GT. NFIT_ITERATION_ALLFILT) .and.
     &       (iter .LE. NFIT_ITERATION_ALLFILT + NFIT_ITER_FITMAGDIF)

        IF ( L0 ) then
           IFLAG    = IFLAG_FITMAGDIF_NOMINAL
           NFILT    = NFILT_ALL
           FILTLIST = FILTLIST_FIT
        ELSE IF ( L1 ) THEN
           IFLAG    = IFLAG_FITMAGDIF_1FILT
           NFILT    = 1
           FILTLIST = FILTER_FITMAGDIF
        ELSE
           IFLAG    = IFLAG_FITMAGDIF_XFILT
           NFILT    = NFILT_ALL
           FILTLIST = FILTLIST_FIT
           CTMP = '(' // FILTER_FITMAGDIF(1:1)//'-band deweighted)'
        ENDIF


        write(6,20) iter, NFILT, FILTLIST(1:NFILT), ctmp
 20     format(T10,'ITER=',I1,' -> NFILT = ', I2, 2x, A, 3x, A)
        CALL FLUSH(6)

         IFLAG_FITMAGDIF(iter) = IFLAG
         NFILT_FITMAGDIF(iter) = NFILT
         FILTLIST_FITMAGDIF(iter) = FILTLIST
 100  CONTINUE

      RETURN
      END   ! end of FITMAGDIF_INI

C =====================================
CDECK  ID>,  MAGDIFPREP. 
      SUBROUTINE FITMAGDIF_PREP(ITER)

c March, 2013
c Called before fit-iteration ITER to prepare fit-iteration ITER
c for fitting either FILTER_FITMAGDIF or all filters except this one.
c
c -----------------------

      IMPLICIT NONE

c subroutine args

      INTEGER ITER ! (I) SN index and fit iteration

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,MAGDIFCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c Mar 2013: for FILTER_FITMAGDIF option

      INTEGER
     &   NFIT_ITER_FITMAGDIF
     &  ,IFLAG_FITMAGDIF_NOMINAL
     &  ,IFLAG_FITMAGDIF_1FILT  ! fit only test filter
     &  ,IFLAG_FITMAGDIF_XFILT  ! exclude test filter
     &  ,IFILTOBS_FITMAGDIF     ! absolute index
     &  ,IFILT_FITMAGDIF        ! sparse survey-filter index

      PARAMETER (
     &   NFIT_ITER_FITMAGDIF     = 1    ! Number of fit-iters per test
     &  ,IFLAG_FITMAGDIF_NOMINAL = 0
     &  ,IFLAG_FITMAGDIF_1FILT   = 1
     &  ,IFLAG_FITMAGDIF_XFILT   = 2
     &      )

      INTEGER
     &   IFLAG_FITMAGDIF(MXITER)  ! 1-> one filter fit, 2-> complement
     &  ,NFILT_FITMAGDIF(MXITER)  ! NFILT to fit per iteration

      CHARACTER
     &   FILTLIST_FITMAGDIF(MXITER)*(MXFILT_ALL) ! filter-list per iteration

      REAL
     &   FITMAG_1FILT, FITMAGERR_1FILT
     &  ,FITMAG_XFILT, FITMAGERR_XFILT
     &  ,FITMAGDIF, FITERRDIF
     &  ,FITPROB_1FILT, FITPROB_XFILT

      COMMON / MAGDIFCOM / IFLAG_FITMAGDIF, NFILT_FITMAGDIF
     &    ,IFILTOBS_FITMAGDIF, IFILT_FITMAGDIF
     &    ,FILTLIST_FITMAGDIF
     &    ,FITMAG_1FILT, FITMAGERR_1FILT
     &    ,FITMAG_XFILT, FITMAGERR_XFILT
     &    ,FITMAGDIF, FITERRDIF
     &    ,FITPROB_1FILT, FITPROB_XFILT


      LOGICAL LMATCH, USE
      INTEGER ipar, ifilt, ifiltdef, iflag, LL
      CHARACTER CFILTDEF*2

C -------------- BEGIN -----------

c check global flag
      IF ( FILTER_FITMAGDIF .EQ. '' ) RETURN

c bail on the nominal ALLFILT interations
      IF ( ITER .LE. NFIT_ITERATION_ALLFILT ) RETURN

c =============================================
c store ALLFILT results just before doing first 2-band fit

      IF ( ITER .EQ. NFIT_ITERATION_ALLFILT + 1 ) THEN

c store original USE_FILT(IFILT) and FITPAR to keep track of which
c filters can be used.
         ALLFILTLIST_FIT   = FILTLIST_FIT_USE
         NOBS_ALLFILT      = NFILT_OBS_USEFIT
         DO IFILTDEF = 1, MXFILT_ALL
           USE_ALLFILT(IFILTDEF) = USE_FILT(IFILTDEF)
         ENDDO

         DO ipar = 1, MXFITPAR
            FITVAL_ALLFILT(ipar) = FITVAL(ipar,ITER-1)
            FITERR_ALLFILT(ipar) = FITERR(ipar,ITER-1)
         ENDDO

c  init final results to dummy values.

         FITMAG_1FILT    = 99.
         FITMAG_XFILT    = 99.
         FITMAGERR_1FILT = 99.
         FITMAGERR_XFILT = 99.
         FITMAGDIF       = 99.
         FITERRDIF       = -9.0
         FITPROB_1FILT   = -9.0
         FITPROB_XFILT   = -9.0
      ENDIF


c make sure that test filter is on the list; otherwise bail out.

      IF ( .not. USE_ALLFILT(IFILTOBS_FITMAGDIF)  ) RETURN

c reset global list of filters to fit.
      FILTLIST_FIT_USE = ''
      NFILT_OBS_USEFIT = 0

c always restore INIVAL and INISTP

      DO ipar = 1, MXFITPAR
         INIVAL(ipar)  = FITVAL_ALLFILT(ipar)
         INISTP(ipar)  = FITERR_ALLFILT(ipar)
      ENDDO

c always restore FUDGE_FITERR params.

      FUDGE_FITERR_PASSBANDS = 'NULL'
      FUDGE_FITERR_MAXFRAC   = 0.0

c -----------------
c if done with all test fits, do nominal fit again so that
c analysis variables correspond to nominal fit.

      IF ( ITER .EQ. NFIT_ITERATION ) THEN

         FILTLIST_FIT_USE = ALLFILTLIST_FIT
         NFILT_OBS_USEFIT = NOBS_ALLFILT

         DO IFILTDEF = 1, MXFILT_ALL
           USE_FILT(IFILTDEF) = USE_ALLFILT(IFILTDEF)
         ENDDO

         CALL INIT_FUDGE_FITERR
         RETURN   ! bail out on last ALLFIT iteration
      ENDIF

      IFLAG = IFLAG_FITMAGDIF(iter)
      NFILT_OBS_USEFIT = 0


c fix all params except for the overall scale/distance parameter
      INISTP(IPAR_SHAPE)     = 0.0    ! fix stretch/lumipar parameter
      INISTP(IPAR_PEAKMJD)   = 0.0    ! fix time of peak

      IF ( IFLAG .EQ. IFLAG_FITMAGDIF_1FILT ) THEN
         INISTP(IPAR_COLOR)     = 0.0    ! fix color param
      ELSE
         INISTP(IPAR_COLOR)     = 0.2
      ENDIF

c use FUDGE_FITER_XXX parameters to de-wieght test filter
c to effectively exclude it.
      IF ( IFLAG .EQ. IFLAG_FITMAGDIF_XFILT ) THEN
         FUDGE_FITERR_PASSBANDS   = FILTER_FITMAGDIF
         FUDGE_FITERR_MAXFRAC     =  999.0
         FUDGE_FITERR_TREST(1)    =  -30.0
         FUDGE_FITERR_TREST(2)    = +200.0
         FUDGE_FITERR_RESTLAM(1)  =  200.0
         FUDGE_FITERR_RESTLAM(2)  = 30000.
      ENDIF


      DO 200 IFILTDEF = 1, MXFILT_ALL
        USE_FILT(IFILTDEF) = .FALSE.
        USE   = .FALSE.
        CFILTDEF = FILTDEF_STRING(IFILTDEF:IFILTDEF)

        LMATCH = IFILTDEF .EQ. IFILTOBS_FITMAGDIF

        IF ( IFLAG .EQ. IFLAG_FITMAGDIF_1FILT ) THEN
          IF ( LMATCH )  USE = .TRUE.
        ELSE
          USE = .TRUE.
        ENDIF

        IF ( USE .and. USE_ALLFILT(IFILTDEF) ) THEN
          NFILT_OBS_USEFIT   = NFILT_OBS_USEFIT + 1
          USE_FILT(IFILTDEF) = .TRUE.

          LL = NFILT_OBS_USEFIT - 1
          FILTLIST_FIT_USE = FILTLIST_FIT_USE(1:LL) //
     &          CFILTDEF(1:1)
        ENDIF

 200  CONTINUE

      write(6,40) SNLC_CCID(1:ISNLC_LENCCID),
     &     ITER, FILTLIST_FIT_USE(1:NFILT_OBS_USEFIT)
 40   format(T5,'FITMAGDIF_PREP(CID=',A,' ITER=',I1,') -> fit  ', A)
      call flush(6)

      CALL INIT_FUDGE_FITERR

      RETURN
      END     ! end of FITMAGDIF_PREP


C =====================================
CDECK  ID>,  MAGDIFCALC. 
      SUBROUTINE FITMAGDIF_CALC(ITER)

c Computations for stored quantities.
c May 8 2013: compute and store FITPROB_1FILT & FITPROB_XFILT
c Feb 20 2017: load PEAKMAG_OBS_MODEL array using sparse IFILT
c
      IMPLICIT NONE

c subroutine args

      INTEGER ITER ! (I) SN index and fit iteration

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,MAGDIFCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c Mar 2013: for FILTER_FITMAGDIF option

      INTEGER
     &   NFIT_ITER_FITMAGDIF
     &  ,IFLAG_FITMAGDIF_NOMINAL
     &  ,IFLAG_FITMAGDIF_1FILT  ! fit only test filter
     &  ,IFLAG_FITMAGDIF_XFILT  ! exclude test filter
     &  ,IFILTOBS_FITMAGDIF     ! absolute index
     &  ,IFILT_FITMAGDIF        ! sparse survey-filter index

      PARAMETER (
     &   NFIT_ITER_FITMAGDIF     = 1    ! Number of fit-iters per test
     &  ,IFLAG_FITMAGDIF_NOMINAL = 0
     &  ,IFLAG_FITMAGDIF_1FILT   = 1
     &  ,IFLAG_FITMAGDIF_XFILT   = 2
     &      )

      INTEGER
     &   IFLAG_FITMAGDIF(MXITER)  ! 1-> one filter fit, 2-> complement
     &  ,NFILT_FITMAGDIF(MXITER)  ! NFILT to fit per iteration

      CHARACTER
     &   FILTLIST_FITMAGDIF(MXITER)*(MXFILT_ALL) ! filter-list per iteration

      REAL
     &   FITMAG_1FILT, FITMAGERR_1FILT
     &  ,FITMAG_XFILT, FITMAGERR_XFILT
     &  ,FITMAGDIF, FITERRDIF
     &  ,FITPROB_1FILT, FITPROB_XFILT

      COMMON / MAGDIFCOM / IFLAG_FITMAGDIF, NFILT_FITMAGDIF
     &    ,IFILTOBS_FITMAGDIF, IFILT_FITMAGDIF
     &    ,FILTLIST_FITMAGDIF
     &    ,FITMAG_1FILT, FITMAGERR_1FILT
     &    ,FITMAG_XFILT, FITMAGERR_XFILT
     &    ,FITMAGDIF, FITERRDIF
     &    ,FITPROB_1FILT, FITPROB_XFILT


      LOGICAL DO_MAGDIF, DO_LCPLOT
      INTEGER IFLAG, IFILTOBS, LCID, NFUNPLOT, NDOF, IFILT
      REAL    ERR1, ERR2, FITPROB
      REAL*8  CHI8, PROB8

      CHARACTER CCID*40

c function
      REAL*8  PROB_CHI2NDOF
      LOGICAL DOPLOT_SNLC

C ------------ BEGIN -------------

c check global flag
      IF ( FILTER_FITMAGDIF .EQ. '' ) RETURN

c bail on the nominal ALLFILT interations
      IF ( ITER .LE. NFIT_ITERATION_ALLFILT ) RETURN
      IF ( ITER .EQ. NFIT_ITERATION         ) RETURN

c bail if test filter is not part of fit.
      IF ( .not. USE_ALLFILT(IFILTOBS_FITMAGDIF)  ) RETURN

c strip off useful info
      IFLAG    = IFLAG_FITMAGDIF(ITER)
      IFILTOBS = IFILTOBS_FITMAGDIF
      IFILT    = IFILTDEF_INVMAP_SURVEY(IFILTOBS) ! sparse index

c store peakMag

      CALL PEAKMAG_CALC(IFILTOBS, 'OBS')

c compute fit prob for each iteration (May 2013)
      NDOF     = NEPOCH_FIT(0) - NFITPAR(0)
      CHI8     = DBLE( FCN_FITCHI2(0) )
      PROB8    = PROB_CHI2NDOF(CHI8, NDOF)

      IF ( IFLAG .EQ. IFLAG_FITMAGDIF_1FILT ) THEN
c fit only this 1 filter.
         FITMAG_1FILT    = PEAKMAG_OBS_MODEL(IFILT)
         FITMAGERR_1FILT = PEAKMAG_OBS_MODEL_ERR(IFILT)
         FITPROB_1FILT   = SNGL(PROB8)
      ELSE IF ( IFLAG .EQ. IFLAG_FITMAGDIF_XFILT ) THEN
c  with filter Xcluded.
         FITMAG_XFILT    = PEAKMAG_OBS_MODEL(IFILT)
         FITMAGERR_XFILT = PEAKMAG_OBS_MODEL_ERR(IFILT)
         FITPROB_XFILT   = SNGL(PROB8)
      ENDIF

c ----
      DO_LCPLOT = ( ITER < NFIT_ITERATION  ) .and.
     &            ( DOPLOT_SNLC() )

      IF ( DO_LCPLOT ) THEN
         IF ( IFLAG .EQ. IFLAG_FITMAGDIF_1FILT ) THEN
            NFUNPLOT = 3
            CALL SNLCPAK_NFIT(NFUNPLOT)  ! store NFIT
         ENDIF

         LCID = ISNLC_LENCCID
         CCID = SNLC_CCID(1:LCID) // char(0)
         CALL MAKEDIR_OUTPUT(CCID,SNLC_CID,LCID)
         CALL FITANA_STORE()
         CALL SNLCPLOT()
         CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! back to topdir
      ENDIF

c after both fits, compute mag difference & error.

      DO_MAGDIF = ITER .EQ. NFIT_ITERATION-1

      IF ( DO_MAGDIF ) THEN

         FITMAGDIF = FITMAG_XFILT - FITMAG_1FILT ! predicted - measured

         ERR1 = FITMAGERR_1FILT
         ERR2 = FITMAGERR_XFILT
         FITERRDIF = sqrt(ERR1**2 + ERR2**2)

c print one-line summary.

         write(6,50) SNLC_CCID(1:ISNLC_LENCCID),
     &          FILTER_FITMAGDIF(1:1), FITMAGDIF, FITERRDIF
 50      format(T5,'FITMAGDIF(CCID=',A,') : ', A,'(pred-meas) = ',
     &         F6.3, ' +- ', F6.3,' mag ')

      ENDIF

      RETURN
      END    ! FITMAGDIF_CALC

C ========================================
CDECK  ID>,  GTMAGDIF. 
      SUBROUTINE GET_FITMAGDIF(MAGDIF, MAGERR, FITPROB )

c Created Mar 2013.
c Return final results via subroutine args.
c May 8 2013: add FITPROB(2) to output
c
      IMPLICIT NONE
      REAL MAGDIF, MAGERR  ! (O)
      REAL FITPROB(2)      ! (O) fit prob for 1 filter, other filters


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,MAGDIFCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c Mar 2013: for FILTER_FITMAGDIF option

      INTEGER
     &   NFIT_ITER_FITMAGDIF
     &  ,IFLAG_FITMAGDIF_NOMINAL
     &  ,IFLAG_FITMAGDIF_1FILT  ! fit only test filter
     &  ,IFLAG_FITMAGDIF_XFILT  ! exclude test filter
     &  ,IFILTOBS_FITMAGDIF     ! absolute index
     &  ,IFILT_FITMAGDIF        ! sparse survey-filter index

      PARAMETER (
     &   NFIT_ITER_FITMAGDIF     = 1    ! Number of fit-iters per test
     &  ,IFLAG_FITMAGDIF_NOMINAL = 0
     &  ,IFLAG_FITMAGDIF_1FILT   = 1
     &  ,IFLAG_FITMAGDIF_XFILT   = 2
     &      )

      INTEGER
     &   IFLAG_FITMAGDIF(MXITER)  ! 1-> one filter fit, 2-> complement
     &  ,NFILT_FITMAGDIF(MXITER)  ! NFILT to fit per iteration

      CHARACTER
     &   FILTLIST_FITMAGDIF(MXITER)*(MXFILT_ALL) ! filter-list per iteration

      REAL
     &   FITMAG_1FILT, FITMAGERR_1FILT
     &  ,FITMAG_XFILT, FITMAGERR_XFILT
     &  ,FITMAGDIF, FITERRDIF
     &  ,FITPROB_1FILT, FITPROB_XFILT

      COMMON / MAGDIFCOM / IFLAG_FITMAGDIF, NFILT_FITMAGDIF
     &    ,IFILTOBS_FITMAGDIF, IFILT_FITMAGDIF
     &    ,FILTLIST_FITMAGDIF
     &    ,FITMAG_1FILT, FITMAGERR_1FILT
     &    ,FITMAG_XFILT, FITMAGERR_XFILT
     &    ,FITMAGDIF, FITERRDIF
     &    ,FITPROB_1FILT, FITPROB_XFILT


C ---------- BEGIN ---------

      MAGDIF = 77.   ! different than initialized value of 99
      MAGERR = -7.0
      FITPROB(1) = -9.0
      FITPROB(2) = -9.0

      IF ( FILTER_FITMAGDIF .NE. '' ) THEN
         MAGDIF = FITMAGDIF
         MAGERR = FITERRDIF

         FITPROB(1) = FITPROB_1FILT
         FITPROB(2) = FITPROB_XFILT
      ENDIF

      RETURN
      END


C ================================================
CDECK  ID>,  SIMFIT_IDEAL_INI. 
      SUBROUTINE SIMFIT_IDEAL_INI()

c Created Aug 29 2017
c
c One-time init for IDEAL FIT with FLUX=TRUEFLUX (sims only)
c Do nothing except print message.
c
      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

c+CDE,SNANAFIT.

C ---------- BEGIN --------------

      DOFIT_IDEAL_EVENT = .FALSE.
      NFIT_ITERATION_ORIG  = NFIT_ITERATION
      NFIT_ITERATION_IDEAL = MIN(NFIT_ITERATION,2) ! no more than 2 iter for IDEAL fit

      IF ( .NOT. LSIM_SNANA ) SIMFIT_IDEAL_PRESCALE = 0
      IF ( SIMFIT_IDEAL_PRESCALE == 0 ) RETURN

      global_banner =
     &    'SIMFIT_IDEAL_INI: include IDEAL fit using TRUEFLUX'
      CALL PRBANNER ( GLOBAL_BANNER(1:60) )
      print*,'   SIMFIT IDEAL PRESCALE = ', SIMFIT_IDEAL_PRESCALE

      RETURN
      END  ! end SIMFIT_IDEAL_INI

C ===============================================
CDECK  ID>,  SIMFIT_IDEAL_PREP. 
      SUBROUTINE SIMFIT_IDEAL_PREP(ITER)

c Created Aug 29 2017
c Called for each event before fit; prepare to add IDEAL fit.
c
c ITER=0 --> before fitting begings
c ITER>0 --> before fit iteration ITER
c
c
      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      INTEGER ITER ! (I) fit iteration

c local var
      INTEGER EP, EPMIN, EPMAX, IMJD, IFILT_OBS
      REAL*8  PS, MAGOFF, SCALE
      LOGICAL REJECT_PRESCALE  ! function

C ----------------- BEGIN ---------------

      IF ( SIMFIT_IDEAL_PRESCALE == 0 ) RETURN

c check pre-scale on ITER=0 (before fitting begins)

      IF ( ITER .EQ. 0 ) THEN

c check debug flag to NOT change fluxes, but still run the
c fit twice to see if we get the same results.
        IF ( SIMFIT_IDEAL_PRESCALE .EQ. SIMFIT_IDEAL_DEBUG ) THEN
           DOFIT_IDEAL_EVENT = .TRUE.
           NFIT_ITERATION = NFIT_ITERATION_ORIG + NFIT_ITERATION_IDEAL
           RETURN
        ENDIF

        PS = DBLE(SIMFIT_IDEAL_PRESCALE)
        IF ( REJECT_PRESCALE(NCALL_SNANA_DRIVER,PS) ) THEN
           DOFIT_IDEAL_EVENT = .FALSE.
           NFIT_ITERATION = NFIT_ITERATION_ORIG
        ELSE
           DOFIT_IDEAL_EVENT = .TRUE.
           NFIT_ITERATION = NFIT_ITERATION_ORIG + NFIT_ITERATION_IDEAL
           CALL SET_IDEAL_FLUXCAL(+1)  ! set FLUXCAL = TRUEFLUX
        ENDIF

        RETURN
      ENDIF   ! end ITER == 0

c - - - - - - -

      DOFIT_IDEAL = (ITER <= NFIT_ITERATION_IDEAL) ! Dec 2023

c check to restore nominal FLUXCAL for normal fit with Poisson fluctuations
      IF ( ITER .EQ. NFIT_ITERATION_IDEAL+1 ) THEN
        IF ( SIMFIT_IDEAL_PRESCALE .NE. SIMFIT_IDEAL_DEBUG ) THEN
          CALL SET_IDEAL_FLUXCAL(-1)  ! restore SNLC_FLUXCAL
        ENDIF
        CALL LOAD_EPALL(ITER, FITVAL(IPAR_PEAKMJD,ITER) )
      ENDIF

cc      print*,' xxx IDEAL_PREP for NCAL=', NCALL_SNANA_DRIVER

      RETURN
      END    ! SIMFIT_IDEAL_PREP

C =======================================
CDECK  ID>,  SET_IDEAL_FLUXCAL. 
      SUBROUTINE SET_IDEAL_FLUXCAL(OPT)

C Created Aug 30 2017
C OPT > 0 --> set SNLC_FLUXCAL = TRUEFLUX
C OPT < 0 --> restore original FLUXCAL
c
c Jan 28 2018:  set USESIM_PEAKMJD = T/F
c
      IMPLICIT NONE

      INTEGER OPT


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


      INTEGER IMJD, EPMIN, EPMAX, EP, IFILT_OBS
      REAL FSCALE

C -------------- BEGIN -------------

      IF ( OPT > 0 ) THEN

c   FLUXCAL -> TRUEFLUX
        DO 101 IMJD  = 1, ISNLC_NEWMJD_STORE
          EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,IMJD)
          EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,IMJD)
        DO 102 ep = EPMIN, EPMAX

           SAVE_FLUXCAL(ep) = SNLC_FLUXCAL(ep)

c re-apply mag-system offset
           IFILT_OBS  = ISNLC_IFILT_OBS(ep)
           Fscale     = FLUXSCALE_ZP_FILT(ifilt_obs)
           SNLC_FLUXCAL(ep) = SIM_EPFLUXCAL(ep) * FSCALE ! true flux

102     CONTINUE
101     CONTINUE

c save measured MWEBV, then MWEBV-> TRUE MWEBV
        SAVE_MWEBV     = SNLC_MWEBV
        SAVE_MWEBV_ERR = SNLC_MWEBV_ERR
        SNLC_MWEBV     = SIM_MWEBV
        SNLC_MWEBV_ERR = 0.0
        CALL MWEBV_FLUXCOR()

        USESIM_PEAKMJD              = .TRUE.  ! Jan 28 2018
        USESIM_FITPAR(IPAR_PEAKMJD) = .TRUE.

      ELSE
c        restore original MWEBV & FLUXCAL

          DO 201 IMJD      = 1, ISNLC_NEWMJD_STORE
            EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,IMJD)
            EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,IMJD)
          DO 202 ep = EPMIN, EPMAX
             SNLC_FLUXCAL(ep) = SAVE_FLUXCAL(ep)
202       CONTINUE
201       CONTINUE

          SNLC_MWEBV      = SAVE_MWEBV
          SNLC_MWEBV_ERR  = SAVE_MWEBV_ERR
          CALL MWEBV_FLUXCOR()

          USESIM_PEAKMJD              = .FALSE.  ! Jan 28 2018
          USESIM_FITPAR(IPAR_PEAKMJD) = .FALSE.
      ENDIF

      RETURN
      END     ! end SET_IDEAL_FLUXCAL

C ================================================
CDECK  ID>,  SIMFIT_IDEAL_CALC. 
      SUBROUTINE SIMFIT_IDEAL_CALC(ITER)

C Created Aug 29 2017
C Process IDEAL fit after each fit ITER.
C Jan 28 2018: compute mB from x0
c
      IMPLICIT NONE

      INTEGER ITER ! (I) fit iteration that just completed

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL

c+CDE,SNLCINP.

      INTEGER IPAR
      REAL*8  x0, mB, SALT2MBCALC

C -------------- BEGIN ---------------

      IF ( SIMFIT_IDEAL_PRESCALE == 0 ) RETURN

      IF ( ITER .EQ. 1) THEN
        DO ipar = 1, NFITPAR_MN
           FITPAR_IDEAL(ipar) = 999.
        ENDDO
      ENDIF

c check when to store results of IDEAL fit
      IF ( DOFIT_IDEAL_EVENT .and. ITER .EQ. NFIT_ITERATION_IDEAL) THEN
        DO ipar = 1, NFITPAR_MN
           FITPAR_IDEAL(ipar) = FITVAL(IPAR,ITER)
        ENDDO

c compute mB from x0 (Jan 28 2018)
        x0 = DBLE ( FITPAR_IDEAL(IPAR_x0) )
        mB = SALT2MBCALC(x0)
        FITPAR_IDEAL(IPAR_MB) = SNGL(mB)
      ENDIF

      RETURN
      END   !  SIMFIT_IDEAL_CALC

C ================================================
CDECK  ID>,  FITRESTMAG_INI. 
      SUBROUTINE FITRESTMAG_INI

c Created Feb 10, 2012
c
c One-time init.
c if FITLTER_RESTMAG is set, then add this filter
c to suryey-filter list and re-init kcor file to
c include this filter. Called only once.
c
c --------

      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      INTEGER
     &   NFILT, NTMP, IERR, IFILT, IFILTDEF
     &  ,i, ITER, LL, NPLOT_PER_SN

      CHARACTER CFILT*2

c function
      INTEGER FILTINDX

C ----------------- BEGIN -----------

      IFILTOBS_BRACKET(1) = -999  ! flag that it's NOT a 2-band fit
      IFILTOBS_BRACKET(2) = -999

      NFILTDEF_FITRESTMAG = 0
      IF ( FILTLIST_FITRESTMAG .EQ. '' ) RETURN

      NFILTDEF_FITRESTMAG = INDEX(FILTLIST_FITRESTMAG,' ') - 1
      NFILT = NFILTDEF_FITRESTMAG

      global_banner = 'FITRESTMAG_INI: prepare rest-mag for  '
     &            // FILTLIST_FITRESTMAG(1:NFILT)

      CALL PRBANNER ( GLOBAL_BANNER(1:60) )

c -------------
c init number of LC plots per SN to prepare SNLCPAK utility
      NPLOT_PER_SN = NFILTDEF_FITRESTMAG + 1    ! each filter, and total
      CALL SNLCPAK_NFIT_PER_SN(NPLOT_PER_SN)   ! see sntools_output.c

c ------------

      NFILTDEF_SURVEY_ORIG    = NFILTDEF_SURVEY

      DO 100 i = 1, NFILT
         CFILT                  = FILTLIST_FITRESTMAG(i:i)
         IFILTDEF_FITRESTMAG(i) = FILTINDX(CFILT)
         IFILTDEF               = IFILTDEF_FITRESTMAG(i)

c add FILTLIST_FITRESTMAG to list of SURVEY_FILTERS

c skip this filter if it is already defined as a survey filter.
         IFILT     = IFILTDEF_INVMAP_SURVEY(IFILTDEF)
         IF ( IFILT .GT. 0 ) THEN
           write(6,20) CFILT
20         format(T8,A1,'-filter already defined -> skip')
           GOTO 100
         ELSE
           write(6,21) CFILT, IFILTDEF
21         format(T8,'Add ',A1,'-filter to SURVEY_FILTERS list',2x,
     &          '(IFILTDEF=',I2,')'  )
         ENDIF
         CALL FLUSH(6)

        NTMP            = NFILTDEF_SURVEY
        SURVEY_FILTERS  = SURVEY_FILTERS(1:NTMP) // CFILT(1:1)
        NFILTDEF_SURVEY = NFILTDEF_SURVEY + 1

        IFILTDEF_INVMAP_SURVEY(IFILTDEF)     = NFILTDEF_SURVEY
        IFILTDEF_MAP_SURVEY(NFILTDEF_SURVEY) = IFILTDEF

100   CONTINUE


c -------- adjust NFIT_ITERATION ----------------

c add NFIT_ITERATION for each new filter
      NFIT_ITERATION_ALLFILT = NFIT_ITERATION
      NFIT_ITERATION      =
     &       NFIT_ITERATION_ALLFILT        ! nominal fit, all bands
     &     + NFIT_ITER_FITRESTMAG*NFILT    ! 2-band fits
     &     + 1                             ! nominal again
     &     + 1                             ! nominal again (Dec 11 2014)


      IF ( NFIT_ITERATION .GT. MXITER ) THEN
        write(c1err,661) NFIT_ITERATION
661     format('NFIT_ITERATION = ', I2,' exceeds bound.')
        write(c2err,662) MXITER
662     format('MXITER = ', I2)
        CALL MADABORT("FITRESTMAG_INI", c1err, c2err )
      ENDIF

      write(6,40) NFIT_ITERATION_ALLFILT, NFIT_ITERATION
40    format(T8,'NFIT_ITERATION = ',I2, ' -> ', I2 )

c load IFILTDEF_ITER_FITRESTMAG array to store which filter
c to process for each fit-iteration

      ITER     = NFIT_ITERATION_ALLFILT
      DO ifilt = 1, NFILT
      DO i     = 1, NFIT_ITER_FITRESTMAG
         CFILT     = FILTLIST_FITRESTMAG(ifilt:ifilt)
         IFILTDEF  = IFILTDEF_FITRESTMAG(ifilt)
         ITER      = ITER + 1
         IFILTDEF_ITER_FITRESTMAG(ITER) = IFILTDEF
         IFILTSP_ITER_FITRESTMAG(ITER)  = IFILT
         write(6,42) ITER, CFILT
42       format(T12,'Fit-iteration ', I2,' -> ', A )

         ITERLAST_FITRESTMAG(ifilt) = ITER
      ENDDO
      ENDDO

c avoid annoying aborts
      ABORT_ON_NOEPOCHS = .FALSE.  ! Mar 20, 2012

c -------------------------
c print misc info

c check for legacy variable
      if ( LUMIFIX_FITRESTMAG < 998.0 ) THEN
        SHAPEFIX_FITRESTMAG = LUMIFIX_FITRESTMAG
      endif
      if ( SHAPEFIX_FITRESTMAG .LT. 900.0 ) then
         write(6,51) 'SHAPEFIX',  SHAPEFIX_FITRESTMAG
      endif
      if ( COLORFIX_FITRESTMAG .LT. 900.0 ) then
         write(6,51) 'COLORFIX', COLORFIX_FITRESTMAG
      endif

51       format(T8,'Evaluate RestMags for ',A,' = ' , F9.3)

      write(6,54) LAMEXTRAP_FITRESTMAG
 54   format(T8,'Allow rest-wavelength extrapolation of +- ',
     &          F5.0,' A ')

      write(6,55) DLAMTOL_FITRESTMAG
 55   format(T8,'Include obs bands within ', F5.0,
     &          ' A of closest bands.')

      write(6,58)       NFILTDEF_SURVEY_ORIG, NFILTDEF_SURVEY
 58   format(T8,'NFILTDEF_SURVEY = ',I3,' -> ', I3)

c -------------------------------------------------
c re-read KCOR file to include FILTLIST_FITRESTMAG
c (user must make sure that FILTLIST_FITRESTMAG is in the kcor file)

      CALL READ_CALIB_WRAPPER(IERR)

      CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! back to topdir

c check that added filter(s) are all in the KCOR file.
c Abort if any filter is missing.

      DO 200 i = 1, NFILT
         CFILT          = FILTLIST_FITRESTMAG(i:i)
         IFILTDEF       = IFILTDEF_FITRESTMAG(i)
         IF ( .NOT. LFILTDEF_OBS(ifiltdef)  ) THEN
           c1err = 'FILTLIST_FITRESTMAG = ' // cfilt //
     &            ' is not in kcor file.'
           c2err = 'Check ' // KCOR_FILE
           CALL MADABORT("FITRESTMAG_INI", c1err, c2err )
         ENDIF
200   CONTINUE

c set flag so that SURVEY_FILTERS are NOT re-read
c if another version header is read.
      FREEZE_SURVEY_FILTERS = .TRUE.

      RETURN
      END

C =====================================
CDECK  ID>,  FITRESTMAG_PREP. 
      SUBROUTINE FITRESTMAG_PREP(ITER)

c Feb 12, 2012
c Called before fit-iteration ITER to prepare fit-iteration ITER
c for fitting FILTLIST_FITRESTMAG. Do nothing for first 1/2 of iterations
c to get t0 and stretch. For 2nd half of iterations keep only
c the two observer bands that bracket FILTLIST_FITRESTMAG.
c
c
c Apr 24 2014:
c  Re-do SNRMAX logic; apply cut to mask filters before calling
c  BRACKET_IFILT_OBS() function, rather than applying SNRMAX cut
c  to the filters found by BRACKET_IFILT_OBS.  New logic is more
c  efficient. Should fix problem at z ~ 0.4 in which g&r are
c  BRACKET filters but then g fails SNRMAX cut; now it will find
c  r&i instead.
c
c Dec 3 2014: for photo-z fit, set Z=ZPHOT instead of SNLC_REDSHIFT.
c
c Mar 26 2020
c  Refactor to use new BRACKET_FILTERLIST with DLAM_TOL so that
c  more than 2 bands can be included if some bands have very
c  similar central wavelengths.
c
c -----------------------

      IMPLICIT NONE

c subroutine args

      INTEGER ITER ! (I) SN index and fit iteration

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      INTEGER
     &   i, IFILT, IFILTDEF, IFILT_TMP, IF1, IF2
     &  ,J, JKEEP, LL, NBRA, NTRY, itry, ITERLAST, IPAR
     &  ,IFILTDEF_MAP_SAVE(MXFILT_OBS)

      REAL LAMAVG, LAMREST(3), LAMTMP, Z, DLAM_TOL
      REAL SNRMAX, SNRMAX1, SNRMAX2
      CHARACTER CFILTOBS_LIST*(MXFILT_OBS), CTMP*4, CFILTDEF*2

      LOGICAL L_BRACKET, L_MATCH, L_USE, L_SNR, L_KEEP
      LOGICAL SKIPTEST, LSNR, LSNR1, LSNR2

c function
      INTEGER BRACKET_FILTERLIST, BRACKET_IFILT_OLD

c -------------------- BEGIN ----------------

      IF ( ITER .EQ. 1 ) NLCPLOT_FITRESTMAG = 0  ! reset plot-counter

c default flag is NOT 2-band fit;
c setting IFILTOBS_BRACKET below --> 2-band fit
      IFILTOBS_BRACKET(1) = -999
      IFILTOBS_BRACKET(2) = -999

c check global flag
      IF ( NFILTDEF_FITRESTMAG .LE. 0 ) RETURN

c bail on the nominal ALLFILT interations
      IF ( ITER .LE. NFIT_ITERATION_ALLFILT ) RETURN

c =============================================
c store ALLFILT results just before doing first 2-band fit

      IF ( ITER .EQ. NFIT_ITERATION_ALLFILT + 1 ) THEN

         DO i = 1, NFILTDEF_FITRESTMAG
            FITRESTMAG(i)     = 999.
            FITRESTMAG_ERR(i) = 999.
         ENDDO

c store original USE_FILT(IFILT) and FITPAR to keep track of which
c filters can be used.
         ALLFILTLIST_FIT   = FILTLIST_FIT_USE
         NOBS_ALLFILT      = NFILT_OBS_USEFIT
         DO IFILT = 1, MXFILT_ALL
           USE_ALLFILT(IFILT) = USE_FILT(IFILT)
         ENDDO

         DO ipar = 1, MXFITPAR
             FITVAL_ALLFILT(ipar) = FITVAL(ipar,ITER-1)
             FITERR_ALLFILT(ipar) = FITERR(ipar,ITER-1)
         ENDDO

      ENDIF

c -------------------------------------------
c reset global list of filters to fit.
      FILTLIST_FIT_USE = ''
      NFILT_OBS_USEFIT = 0

c always restore INIVAL and INISTP
c Note that 1st IPAR_ITER param is not restored.

      DO ipar = 1, MXFITPAR
         IF ( ipar .NE. IPAR_ITER ) then
           INIVAL(ipar)  = FITVAL_ALLFILT(ipar)
           INISTP(ipar)  = FITERR_ALLFILT(ipar)
         ENDIF
      ENDDO

c -----------------------------------------------------------
c if done with all 2-band fits, do nominal fit again so that
c analysis variables correspond to nominal fit rather than
c to the last 2-band fit.

      ITERLAST = ITERLAST_FITRESTMAG(NFILTDEF_FITRESTMAG)
      IF ( ITER .GT. ITERLAST ) THEN

         FILTLIST_FIT_USE = ALLFILTLIST_FIT
         NFILT_OBS_USEFIT = NOBS_ALLFILT

         DO IFILT = 1, MXFILT_ALL
           USE_FILT(IFILT) = USE_ALLFILT(IFILT)
         ENDDO

         RETURN   ! bail out on last ALLFIT iteration
      ENDIF

c set tolerance for including bands close in wavelength
      DLAM_TOL = DLAMTOL_FITRESTMAG

c =========================================

c strip off filter to process for this fit-iteration
      IFILTDEF = IFILTDEF_ITER_FITRESTMAG(ITER)
      CFILTDEF = FILTDEF_STRING(IFILTDEF:IFILTDEF)
      if ( IFILTDEF .LE. 0 .OR. IFILTDEF .GT. MXFILT_ALL ) then
         write(C1ERR,161) ITER,IFILTDEF
161      format('Invalid IFILTDEF_ITER_FITRESTMAG(ITER=',I2,') = ', I4)
         C2ERR = 'Check FILTLIST_FITRESTMAG in &FITINP'
         CALL MADABORT('FITRESTMAG_PREP', C1ERR, C2ERR)
      endif


c for remainder of the iterations (i.e., 2-band fits)
c  - float only color and distance/x0 (i.e,, fix PKMJD and LUMIPAR)
c  - keep only observer bands that bracket FILTLIST_FITRESTMAG
c  - fix redshift (for photo-z fits)

      INISTP(IPAR_SHAPE)     = 0.0  ! fix stretch/lumipar parameter
      INISTP(IPAR_PEAKMJD)   = 0.0  ! fix time of peak

      IF ( DOFIT_PHOTOZ ) THEN
         ipar = IPAR_zPHOT
         INISTP(ipar) = 0.0
         Z    =  FITVAL_ALLFILT(ipar)
      ELSE
         Z  = SNLC_REDSHIFT
      ENDIF

c set list of LAMREST to try.
      LAMAVG        = FILTOBS_LAMAVG(ifiltdef)
      LAMREST(1)    = LAMAVG
      LAMREST(2)    = LAMAVG + LAMEXTRAP_FITRESTMAG
      LAMREST(3)    = LAMAVG - LAMEXTRAP_FITRESTMAG
      IF ( LAMEXTRAP_FITRESTMAG .GT. 0.1 ) THEN
         NTRY = 3
      ELSE
         NTRY = 1
      ENDIF

c ---------------------------------------------------
c Find obs-filters that bracket FILTLIST_FITRESTMAG
c Before searching for two nearest bands,  EXCLUDE filter if
c   * it's a FITRESTMAG filter (so it does not find itself)
c   * it fails SNRMAX cut  e.g., if g&r are the closest two bands
c     but g fails SNRMAX cut, the BRACKET function will return
c     ri instead.
c
c Note that loop is over ALL filters, not just FITRESTMAG filters.
c

      DO ifilt = 1, NFILTDEF_SURVEY

         IFILTDEF_MAP_SAVE(ifilt) = IFILTDEF_MAP_SURVEY(ifilt)
         IFILTDEF                 = IFILTDEF_MAP_SURVEY(ifilt)  !absolute indx
         if ( ifilt .GT. NFILTDEF_SURVEY_ORIG ) then
            IFILTDEF_MAP_SURVEY(ifilt) = -999
         endif

         ! apply SNRMAX cut only if SNRMAX is defined
         SNRMAX   = SNLC_SNRMAX_FILT(ifilt)
         SKIPTEST = .not. LFILTDEF_SNRMAX(IFILTDEF)
         LSNR     = SKIPTEST .or. (SNRMAX .GE. CUTWIN_SNRMAX2(1) )

         if ( .NOT. LSNR ) then
            IFILTDEF_MAP_SURVEY(ifilt) = -999
         endif
      ENDDO  ! end ifilt loop over all filters

c -----------------------

      L_BRACKET = .FALSE.
      DO 440 itry = 1, NTRY

c Sep 2013: beware that BRACKET_IFILT_OBS() checks all filters
c selected by snana, not just the ones in FILTLIST_FIT.
c Use EPCUT_SNRMIN to reject extra filters.

         LAMTMP = LAMREST(itry)

c new default, Mar 28 2020
          NBRA = BRACKET_FILTERLIST(LAMTMP, DLAM_TOL, Z,
     &            IFILTOBS_BRACKET) ! <== returned

         IF1 = IFILTOBS_BRACKET(1)  ! closest band, low wavelen
         IF2 = IFILTOBS_BRACKET(2)  ! closest band, high wavelen


         IF ( IF1 .LE. 0 ) GOTO 440
         IF ( IF2 .LE. 0 ) GOTO 440

c check if IFILTOBS_BRACKET(1:2) are valid
         L_USE = USE_ALLFILT(IF1) .and. USE_ALLFILT(IF2)
         L_BRACKET = (NBRA >= 2) .and. L_USE

         if ( L_BRACKET ) goto 444
440   CONTINUE  ! end itry

c --------------------
444   CONTINUE

c ------------------
c reset filter map

      DO ifilt = 1, NFILTDEF_SURVEY
         IFILTDEF_MAP_SURVEY(ifilt) = IFILTDEF_MAP_SAVE(ifilt)
      ENDDO

      IF ( .NOT. L_BRACKET ) GOTO 455


c print message for which filter to fit, or to skip.
455   CONTINUE

      IF ( L_BRACKET ) THEN
         do i = 1, NBRA
            IFILTDEF = IFILTOBS_BRACKET(i)
            CFILTOBS_LIST(i:i) =  FILTDEF_STRING(IFILTDEF:IFILTDEF)
         enddo
         CTMP     = 'Fit '
      ELSE
         CTMP     = 'Skip'
         CFILTOBS_LIST =  '??'
      ENDIF

      LL = ISNLC_LENCCID
      write(6,20) CTMP, CFILTDEF,
     &     SNLC_CCID(1:LL), CFILTOBS_LIST(1:NBRA)
20    format(T5, A,' RestMag-',A,'  for  CID = ',A,
     &               3x, 'ObsFilt = ',A,A)
      CALL FLUSH(6)


c Turn off filters that do not bracket FILTLIST_FITRESTMAG.
c If either of the BRACKET filters is not defined then
c turn off ALL filters so that nothing passes.


      DO 200 ifilt   = 1, NFILTDEF_SURVEY

         L_KEEP      = .FALSE.
         L_USE       = .FALSE.

         IFILT_TMP   = IFILTDEF_MAP_SURVEY(ifilt)
         L_USE       = USE_ALLFILT(IFILT_TMP)

      DO 202 j       = 1, NBRA  ! xxx 2 -> NBRA
           L_MATCH   = IFILT_TMP .EQ. IFILTOBS_BRACKET(J)
           IF ( L_BRACKET .and. L_MATCH .AND. L_USE ) THEN
               L_KEEP  = .TRUE.
               JKEEP = J
           ENDIF
 202  CONTINUE  ! J

         if ( L_KEEP ) then
            LL = INDEX ( FILTLIST_FIT_USE, ' ' ) - 1
            FILTLIST_FIT_USE = FILTLIST_FIT_USE(1:LL) //
     &            cfiltobs_list(jkeep:jkeep)
            NFILT_OBS_USEFIT = NFILT_OBS_USEFIT + 1
            USE_FILT(IFILT_TMP) = .TRUE.
         else
            USE_FILT(IFILT_TMP) = .FALSE.
         endif

 200  CONTINUE  ! ifilt

c --------------------
c sanity check

      IF ( L_BRACKET .and. NFILT_OBS_USEFIT < 2 ) THEN
         write(c1err,601)  NFILT_OBS_USEFIT
601      format('L_BRACKET=T  but  NFILT_OBS_USEFIT = ',I2)
         write(c2err,602) SNLC_CCID, ITER, CFILTDEF
602      format('CID=',A8, 2x, 'ITER=',I1,' -> RestFilt=',A1)
         CALL MADABORT('FITRESTMAG_PREP', C1ERR, C2ERR)
      ENDIF


      RETURN
      END    ! end of FITRESTMAG_PREP(ITER)


C ========================================
CDECK  ID>,  BRACKET_IFILT_OLD. 
      INTEGER FUNCTION BRACKET_IFILT_OLD (
     &          LAMREST, Z, IFILTOBS_BRACKET )

c !!!!!!!!!!!!!!!!!!!
c !!!! Mar 25 2020: SLATED TO BECOME OBSOLETE !!!!
c !!!!!!!!!!!!!!!!!!!
c -----------------------------------------
c Feb 12, 2012
c Return IFILTOBS_BRACKET(2) (filter indices) that brackets
c LAMREST in the rest-frame. In the loop over SURVEY filters,
c IFILT_OBS = -999 is a flag to ignore this filter.
c
c Return number of bracket-filters found; 2 => success.
c
c ------------------------------------------

      IMPLICIT NONE

c subroutine args.

      REAL LAMREST   ! (I) rest-frame lambda to match
      REAL Z         ! (I) redshift
      INTEGER
     &  IFILTOBS_BRACKET(2) ! (O) IFILTOBS that brackets LAMREST

c local var

C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFILT, IFILTOBS, JLOHI, NFILT
      REAL Z1, LAMZ, LAMDIF, LAMDIFMIN(2)

C ------------- BEGIN ------------

      Z1 = 1.0 + z

      LAMDIFMIN(1) = 99999999.
      LAMDIFMIN(2) = 99999999.

      IFILTOBS_BRACKET(1) = -9
      IFILTOBS_BRACKET(2) = -9

      DO 100 ifilt = 1, NFILTDEF_SURVEY

         if ( .not. EXIST_FILT(ifilt) ) goto 100

         ifiltobs = IFILTDEF_MAP_SURVEY(ifilt)
         if ( ifiltobs .EQ. -999 ) goto 100

         LAMZ   = FILTOBS_LAMAVG(ifiltobs)/Z1
         LAMDIF = ABS(LAMZ-LAMREST)

         IF ( LAMZ .LE. LAMREST ) THEN
            JLOHI = 1
         ELSE
            JLOHI = 2
         ENDIF

         if ( LAMDIF .LT. LAMDIFMIN(JLOHI) ) then
             LAMDIFMIN(JLOHI)        = LAMDIF
             IFILTOBS_BRACKET(JLOHI) = IFILTOBS
         endif

100   CONTINUE

c set function value

      NFILT = 0
      IF ( IFILTOBS_BRACKET(1) .GT. 0 ) NFILT = NFILT + 1
      IF ( IFILTOBS_BRACKET(2) .GT. 0 ) NFILT = NFILT + 1

      BRACKET_IFILT_OLD = NFILT

      RETURN
      END

C ========================================
CDECK  ID>,  BRACKET_FILTERLIST. 
      INTEGER FUNCTION BRACKET_FILTERLIST (
     &          LAMREST, DLAM_TOL, Z, IFILTOBS_BRACKET )

c -----------------------------------------
c Mar 25 2020
c Return IFILTOBS_BRACKET (indices) of obs-filters that bracket
c LAMREST in the rest-frame.
c In the loop over SURVEY filters, IFILT_OBS = -999 is a flag
c (externally set) to ignore this filter.
c
c This function originally returned just 2 bands: one below and
c one above the target LAMREST. Now it has been refactored to
c return all filters within DLAM_TOL of closest filters.
c
c Original motivatoin is to work for LOWZ in which each band
c is broken into several bands covering different time periods.
c
c
c Inputs:
c   LAMREST   : rest-frame wavelength to bracket
c   DLAM_TOL  : combine obs filters withing this tolerance
c   Z         : redshift
c
c Output:
c   IFILTOBS_BRACKET(1) : closest band with LAM/z1 < LAMREST
c   IFILTOBS_BRACKET(2) : closest band with LAM/z1 > LAMREST
c   IFILTOBS_BRACKET(3) : optional additional band within DLAM_TOL
c   IFILTOBS_BRACKET(4) : optional additional band within DLAM_TOL
c   etc ...
c
c Function returns number of bands in IFILTOBS_BRACKET list.
c If only low or high bands are found, function returns 1.
c Function returnig 2 or larger is flag for success.
c Example, if filters a,b,c all have LAM/z1 < LAMREST, then
c function returns 1. But if there is also filter d with
c LAM/z1>LAMREST, then function returns 4.
c
c ------------------------------------------

      IMPLICIT NONE

c subroutine args.

      REAL LAMREST   ! (I) rest-frame lambda to match
      REAL DLAM_TOL  ! (I) tolerance to accept multiple bracket filters
      REAL Z         ! (I) redshift

      INTEGER
     &  IFILTOBS_BRACKET(*) ! (O) IFILTOBS that brackets LAMREST

c local var

C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER IFILT, NFILT, IFILTOBS, IFILTOBS_LO, IFILTOBS_HI, JLOHI
      REAL    Z1, LAMZ, LAMZ_LO, LAMZ_HI, LAMDIF, LAMDIFMIN(2)
      CHARACTER  CFILT*2

C ------------- BEGIN ------------

      Z1 = 1.0 + z

      LAMDIFMIN(1) = 99999999.
      LAMDIFMIN(2) = 99999999.

      DO 100 ifilt = 1, NFILTDEF_SURVEY

         if ( .not. EXIST_FILT(ifilt) ) goto 100
         ifiltobs = IFILTDEF_MAP_SURVEY(ifilt)
         if ( ifiltobs .EQ. -999 ) goto 100

         CFILT  = FILTDEF_STRING(IFILTOBS:IFILTOBS)
         LAMZ   = FILTOBS_LAMAVG(ifiltobs)/Z1
         LAMDIF = ABS(LAMZ-LAMREST)

         IF ( LAMZ .LE. LAMREST ) THEN
            JLOHI = 1
         ELSE
            JLOHI = 2
         ENDIF

         if ( LAMDIF .LT. LAMDIFMIN(JLOHI) ) then
             LAMDIFMIN(JLOHI)        = LAMDIF
             IFILTOBS_BRACKET(JLOHI) = IFILTOBS
         endif

100   CONTINUE

c set function value

      NFILT = 0
      IFILTOBS_LO = IFILTOBS_BRACKET(1)
      IFILTOBS_HI = IFILTOBS_BRACKET(2)
      IF ( IFILTOBS_LO > 0 ) NFILT = NFILT + 1
      IF ( IFILTOBS_HI > 0 ) NFILT = NFILT + 1
      BRACKET_FILTERLIST = NFILT

      IF ( NFILT < 2       ) RETURN
      IF ( DLAM_TOL < 0.01 ) RETURN

cc      IF ( DLAM_TOL < 1.0E9 ) RETURN ! xxx REMOVE

      LAMZ_LO = FILTOBS_LAMAVG(IFILTOBS_LO)/Z1
      LAMZ_HI = FILTOBS_LAMAVG(IFILTOBS_HI)/Z1

c if we get here, check for more bands with DLAM_TOL ...

      DO 200 ifilt = 1, NFILTDEF_SURVEY

         if ( .not. EXIST_FILT(ifilt) ) goto 200
         ifiltobs = IFILTDEF_MAP_SURVEY(ifilt)
         if ( ifiltobs .EQ. -999 ) goto 200

c skip already defined bracket filters
         if ( ifiltobs == IFILTOBS_LO ) goto 200
         if ( ifiltobs == IFILTOBS_HI ) goto 200

         LAMZ   = FILTOBS_LAMAVG(IFILTOBS)/Z1

c start with lower-wavelength filter
         LAMDIF = ABS(LAMZ-LAMZ_LO)
         if ( LAMZ < LAMZ_LO .and. LAMDIF < DLAM_TOL ) then
            NFILT = NFILT + 1 ; IFILTOBS_BRACKET(NFILT) = ifiltobs
         endif

c higher-wavelength filter
         LAMDIF = ABS(LAMZ-LAMZ_HI)
         if ( LAMZ > LAMZ_HI .and. LAMDIF < DLAM_TOL ) then
            NFILT = NFILT + 1 ; IFILTOBS_BRACKET(NFILT) = ifiltobs
         endif

 200  CONTINUE

      BRACKET_FILTERLIST = NFILT

      RETURN
      END

C =====================================
CDECK  ID>,  FITRESTCALC. 
      SUBROUTINE FITRESTMAG_CALC(ITER)
c
c Feb 2012:
c If ITER corresponds to the last iteration for a rest-filter,
c compute and fill global FITRESTMAG and FITRESTMAG_IERR
c
c Sep 19 2013: call SNLCPAK to show each single-band fit
c
c Dec 11, 2014: return if ITER > ITERLAST_2BAND to allow more
c                than 1 fit after the 2-band fits.
c ----------------------------------

      IMPLICIT NONE

c subroutine args

      INTEGER ITER ! (I) SN index and fit iteration

c local var


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      INTEGER
     &   IFILTDEF, IFILT, NFUNPLOT, ITERLAST_2BAND
     &  ,LCHAR_CCID, LCHAR_SHAPE, LCHAR_COLOR

      REAL*8
     &   SHAPE_FIT, COLOR_FIT, Z, x0, x0err, x0ref
     &  ,SHAPE, COLOR, MAGCOR

      CHARACTER CFILT*2, CCID*(MXCHAR_CCID)

c function
      REAL*8  GET_DIST8
      LOGICAL DOPLOT_SNLC

C ----------- BEGIN -----------

      IF ( NFILTDEF_FITRESTMAG .LE. 0       ) RETURN
      IF ( ITER .LE. NFIT_ITERATION_ALLFILT ) RETURN

      ITERLAST_2BAND = ITERLAST_FITRESTMAG(NFILTDEF_FITRESTMAG)
      IF ( ITER > ITERLAST_2BAND ) RETURN

c get absolute filter index of rest-frame filter
      IFILTDEF = IFILTDEF_ITER_FITRESTMAG(ITER)
      IFILT    = IFILTSP_ITER_FITRESTMAG(ITER)

c ---------------------------------------
c sanity check on filter indices

      IF (     IFILTDEF .LE. 0
     &   .or.  IFILTDEF .GT. MXFILT_ALL
     &   .or.  IFILT    .LE. 0
     &   .or.  IFILT    .GT. MXFILT_FITRESTMAG
     &     ) THEN
         write(c1err,611) IFILTDEF, IFILT
611        format('Invalid  IFILTDEF=', I5, 3x,'IFILT=',I3)
         write(c2err,612) SNLC_CCID, ITER
612        format('for CID=', A8, 3x, 'and ITER=' ,I2)
         CALL MADABORT('FITRESTMAG_CALC', C1ERR, C2ERR)
      ENDIF
c ---------------------------------------

c proceed with calc only on last iteration for this filter.
      IF ( ITER .NE. ITERLAST_FITRESTMAG(ifilt) ) RETURN

c save fitted SHAPEPAR in case we use a fixed SHAPEPAR for restMag
      SHAPE_FIT  = LCVAL_STORE(IPAR_SHAPE)
      COLOR_FIT  = LCVAL_STORE(IPAR_COLOR)

c set LCVAL_STORE to get rest-frame mag

      IF ( SHAPEFIX_FITRESTMAG .LT. 990.0 ) THEN
        LCVAL_STORE(IPAR_SHAPE) = SHAPEFIX_FITRESTMAG
      ENDIF
      IF ( COLORFIX_FITRESTMAG .LT. 990.0 ) THEN
        LCVAL_STORE(IPAR_COLOR) = COLORFIX_FITRESTMAG
      ENDIF

c store fit-info in local variables (before they get restored!)
      CFILT   = FILTDEF_STRING(IFILTDEF:IFILTDEF)
      SHAPE   = DBLE( LCVAL_STORE(IPAR_SHAPE) )
      COLOR   = DBLE( LCVAL_STORE(IPAR_COLOR)   )

c put this filter on the 'EVAL' list
      CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,ifiltdef), ifiltdef )

c compute peakmag
      CALL PEAKMAG_CALC(ifiltdef, 'REST')

c restore nominal values
      LCVAL_STORE(IPAR_SHAPE)   = SHAPE_FIT
      LCVAL_STORE(IPAR_COLOR)   = COLOR_FIT

c PEAKMAG_REST was evaluated for the best-fit model assuming
c DLMAG=0 or x0=1. But we need the standardization part of x0.
c WARNING: Below is hard-wired for SALT2 ... need to fix for mlcs/snoopy.

      Z      = DBLE(REDSHIFT_FIT)
      x0     = LCVAL_STORE(IPAR_DLMAG)     ! from fit with SHAPE floated
      x0err  = LCERR_STORE(IPAR_DLMAG)     ! idem
      x0ref  = GET_DIST8(Z,SHAPE_FIT,COLOR_FIT,ONE8)
      MAGCOR = -2.5*log10(x0/x0ref)
cc      print*,' xxx MAGCOR = ', MAGCOR,'  for CID=', SNLC_CCID

c save fitted rest mag and error
      FITRESTMAG(IFILT)     = PEAKMAG_REST_MODEL(ifiltdef)
     &                      + MAGCOR

c      FITRESTMAG_ERR(IFILT) = PEAKMAG_REST_MODEL_ERR(ifiltdef)
      FITRESTMAG_ERR(IFILT) = 1.0857*x0err/x0     ! Mar 30 2014

c ------------------------
c print one-line summary.

      LCHAR_CCID  = ISNLC_LENCCID
      LCHAR_SHAPE = INDEX(PARNAME_STORE(IPAR_SHAPE),' ') - 1
      LCHAR_COLOR = INDEX(PARNAME_STORE(IPAR_COLOR),  ' ') - 1

      write(6,20)
     &    CFILT(1:1)
     &   ,SNLC_CCID(1:LCHAR_CCID)
     &   ,FITRESTMAG(IFILT), FITRESTMAG_ERR(IFILT)
     &   ,PARNAME_STORE(IPAR_SHAPE)(1:LCHAR_SHAPE),  SHAPE
     &   ,PARNAME_STORE(IPAR_COLOR)(1:LCHAR_COLOR),  COLOR

20    format(T5,'FitRestMag-',A,'(',A,') = ', F8.3,' +- ' , F6.3,
     &   3x, '(',A,'=',F6.3,  2x,  A,'=',F6.3, ')'   )


c -----------------------------------------------------
c for SALT2, get K-corrected FLUX_REST (Jan 2014)

      IF ( FITMODEL_INDEX .EQ. MODEL_SALT2 ) THEN
         CALL SALT2_FLUXREST(IFILTDEF,SHAPE,COLOR)
      ENDIF

c --------------------------
c check option for single-band plot (Sep 2013)

      IF ( DOPLOT_SNLC() ) THEN

         NLCPLOT_FITRESTMAG = NLCPLOT_FITRESTMAG + 1
         IF ( NLCPLOT_FITRESTMAG .EQ. 1 ) THEN
c problem: if next fit fails we have already committed
c          to NFUNPLOT plots ???
            NFUNPLOT = NFILTDEF_FITRESTMAG + 1
            CALL SNLCPAK_NFIT(NFUNPLOT)  ! store NFIT
         ENDIF

         CCID = SNLC_CCID(1:LCHAR_CCID) // char(0)
         CALL MAKEDIR_OUTPUT(CCID, SNLC_CID, LCHAR_CCID)
         CALL FITANA_STORE()
         CALL SNLCPLOT()
         CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! back to topdir
      ENDIF

      RETURN
      END   ! FITRESTMAG_CALC


C ========================================
CDECK  ID>,  S2FLREST. 
      SUBROUTINE SALT2_FLUXREST(IFILTREST,SHAPE,COLOR)
c ---------------------
c
c Created Jan 2014 by R.Kessler
c
c For each epoch, compute K-correction and load EP_FLUX_REST array.
c
c Dec 31, 2014:   fill I4EP_ALL(ep,IEP_IFILT_REST1)
c
c ---------------------

      IMPLICIT NONE

c subroutine args
      INTEGER IFILTREST      ! (I) absolute value of rest-frame filter
      REAL*8  SHAPE, COLOR   ! (I)
      REAL*8  SHAPE2

c local args


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      INTEGER
     &   IF1, IF2, IFILTOBS, IFILT, IMJD
     &   ,MSKSALT2, NEP, EP, EPMIN, EPMAX

      REAL*8
     &   z1, ZSN, LAMREST, LAMDIF1, LAMDIF2, LAMDIF
     &  ,x0, x1, xx1, c, x2, MWEBV, PKMJD
     &  ,TOBS, Trest, MAGOBS_MODEL, MAGREST_MODEL, MAGERR
     &  ,KCOR, MAGOBS, MAGREST, FLUX_REST, ARG
     &  ,RV, AV,  PARLIST_SN(10), PARLIST_HOST(10)

      LOGICAL LDMP
C ----------------- BEGIN -----------------
C
C determine which of the IFILTOBS_BRACKET is closest to IFILTDEF(rest)
C Note that the rest-frame filter is defined as an obs-filter.

      LDMP = .FALSE.

      Z1      = 1.0 + REDSHIFT_FIT
      LAMREST = FILTOBS_LAMAVG(ifiltrest)
      IF1     = IFILTOBS_BRACKET(1)
      IF2     = IFILTOBS_BRACKET(2)
      LAMDIF1 = ABS(FILTOBS_LAMAVG(IF1)/z1 - LAMREST)
      LAMDIF2 = ABS(FILTOBS_LAMAVG(IF2)/z1 - LAMREST)
      MWEBV   = SNLC_MWEBV

      IF (LAMDIF1 < LAMDIF2 ) THEN
        IFILTOBS = IF1 ; LAMDIF = LAMDIF1
      ELSE
        IFILTOBS = IF2 ; LAMDIF = LAMDIF2
      ENDIF

      IF ( LDMP ) THEN
        print*,' xxxxx ------------------------------------- '
        write(6,60) SNLC_CCID, IFILTREST, IFILTOBS, LAMDIF
 60     format(' xxxxx CID=', A6, 2x,'IFILT[REST,OBS]=',2I3, 3x,
     &          'LAMDIF=',F5.0 )
      ENDIF

      MSKSALT2 = 0   ! -> return mag
      x0       = 1.0
      x1       = SHAPE
      xx1      = SHAPE
      c        = COLOR
      x2       = 0.0  ! ?? Dec 2023
      NEP      = 1
      PKMJD    = LCVAL_STORE(IPAR_PEAKMJD) + MJDOFF
      RV=0.0 ;   AV=0.0

      PARLIST_SN(1) = x0
      PARLIST_SN(2) = x1
      PARLIST_SN(3) = xx1
      PARLIST_SN(4) = c
      PARLIST_SN(5) = x2

      PARLIST_HOST(1) = RV
      PARLIST_HOST(2) = AV
      PARLIST_HOST(3) = -9.0 ! logmass

      DO 101 IMJD      = 1, ISNLC_NEWMJD_STORE
        EPMIN = ISNLC_EPOCH_RANGE_NEWMJD(1,IMJD)
        EPMAX = ISNLC_EPOCH_RANGE_NEWMJD(2,IMJD)

      DO 102 ep = EPMIN, EPMAX

         IF ( IFILTOBS .NE.  ISNLC_IFILT_OBS(ep) ) GOTO 102

         ifilt = IFILTDEF_INVMAP_SURVEY(ifiltobs)

c start with obs-frame
         TOBS    = SNLC8_MJD(ep) - PKMJD
         Trest   = TOBS/z1

         ZSN     = REDSHIFT_FIT
         CALL genmag_salt2( MSKSALT2, IFILTOBS,
     &        PARLIST_SN, PARLIST_HOST, MWEBV, ZSN,ZSN,  NEP, Tobs,
     &        MAGOBS_MODEL, MAGERR )     ! return arg

c now the rest-frame
         ZSN     = 1.0E-6
         CALL genmag_salt2( MSKSALT2, IFILTREST,
     &        PARLIST_SN, PARLIST_HOST, MWEBV, ZSN,ZSN, NEP, Trest,
     &        MAGREST_MODEL, MAGERR )     ! return arg

         KCOR    = MAGREST_MODEL - MAGOBS_MODEL
         MAGOBS  = R4EP_ALL(ep,JEP_DATAMAG)

         IF ( MAGOBS > 0 ) THEN
           MAGREST    = MAGOBS + KCOR - SNLC_DLMAG
           ARG        = 0.4*(ZEROPOINT_FLUXCAL_DEFAULT - MAGREST)
           FLUX_REST  = 10.0**(ARG)
           R4EP_ALL(ep,JEP_DATAFLUX_REST) = FLUX_REST
           I4EP_ALL(ep,IEP_IFILT_REST1)   = IFILTREST
         ELSE
           MAGREST   = -999
           FLUX_REST = -999
         ENDIF

         IF ( LDMP ) THEN
           write(6,61) Trest, MAGOBS, MAGREST
 61        format(' xxxx Trest=',F6.1, 2x, 'MAG[OBS,REST]=',2G12.5 )
           call flush(6)
         ENDIF

 102  CONTINUE  ! ep
 101  CONTINUE  ! IMJD

      RETURN
      END

C ========================================
CDECK  ID>,  GTFITRST. 
      SUBROUTINE GET_FITRESTMAG(IFILT, MAGREST, MAGERR)

C created Mar 2013.
C Return fitted rest-mag and error for this sparse IFILT.
C
      IMPLICIT NONE
      INTEGER  IFILT            ! (I) sparse filter index
      REAL     MAGREST, MAGERR  ! (O)


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG

C ----------- BEGIN ----------
      MAGREST = FITRESTMAG(ifilt)
      MAGERR  = FITRESTMAG_ERR(ifilt)
      RETURN
      END


C =======================================
CDECK  ID>,  LFITFUN_FILT. 
      LOGICAL FUNCTION LFITFUN_FILT(ifilt_obs,ZTEST)
c
c Return T if this filter should be included in fit.
c
c ZTEST > 0 => make z-dependent tests
c ZTEST < 0 => skip z-dependent tests
c
c ---------------------

      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER
     &  ifilt_obs  ! (I) observer filter index

      REAL*8 ZTEST

c local

      INTEGER IFILT_REST, IFILT, OPT
      REAL*8 oneplusZ, LAMZ
      REAL*4 Z4, LMIN4

      LOGICAL DOTEST_Z
      LOGICAL DOTEST_NONZ, ISSURVEY, NOEPOCHS

c function
      INTEGER NEAREST_IFILTDEF_WRAPPER

C --------------- BEGIN ----------------

      LFITFUN_FILT = .FALSE.

c did user request this filter.
      if ( .NOT. DOFIT_FILT(ifilt_obs) ) RETURN

c are there any epochs with this filter.
      ifilt = IFILTDEF_INVMAP_SURVEY(ifilt_obs)
      ISSURVEY = .NOT. LFILTDEF_NONSURVEY(ifilt_obs)
      NOEPOCHS = .NOT. EXIST_FILT(ifilt)
      if ( ISSURVEY .and. NOEPOCHS ) RETURN

      IF ( DOFIT_PHOTOZ ) THEN
        if ( PHOTOZ_DROPFILTER(ifilt_obs)) RETURN ! drop this filter
      ENDIF

c -----------------------------------

      IF ( ZTEST .GT. 0.0 ) THEN

c does this observer filter transform to a valid
c rest-frame lambda range

        oneplusZ  = 1.0 + ZTEST
        LAMZ  = FILTOBS_LAMAVG(ifilt_obs) / oneplusZ

        IF ( LAMZ .LT. RESTLAMBDA_USEFIT(1) ) RETURN
        IF ( LAMZ .GT. RESTLAMBDA_USEFIT(2) ) RETURN

c does this observer filter transform to a valid rest-frame filter

        IF ( LREST_FITMODEL ) THEN
          Z4  = SNGL(ZTEST)
          OPT = OPT_FILTOBS
          ifilt_rest = NEAREST_IFILTDEF_WRAPPER(OPT,ifilt_obs,
     &                       1, Z4, LMIN4 )
          if ( ifilt_rest .LE. 0. ) RETURN
        ENDIF
      ENDIF

c all is OK.

      LFITFUN_FILT = .TRUE.

      RETURN
      END

C =======================================
CDECK  ID>,  LANDOLT_PREP. 
      SUBROUTINE LANDOLT_PREP()
c
c Created Feb 10, 2012
c
c Init stuff related to OPT_LANDOLT.
c Pulled out of FITPAR_PREP.
c
c May 2012: if BX is defined in the KCOR file but is not
c           a SURVEY_FILTER, then define X here as a SURVEY_FILTER.
c           This part was moved from RDKCOR.
c
c ------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER ISTAT, IFILT, i
      CHARACTER CTMP*8, FNAM*16
      LOGICAL   FORCE, LBX
      REAL MAG_PRIMARY

c function
      INTEGER  LANDOLT_INI
      EXTERNAL LANDOLT_INI

C -------------- BEGIN -------------------------

      FNAM = 'LANDOLT_PREP'

c check for Marriner's "LANDOLT" option
c OPT_LANDOLT bits (lsb=0):
c   bit0 : Landolt => Bessell in rest-frame (BD17)
c   bit1 : Bessell => Landolt in obs-frame  (BD17)
c   bit2 : idem but in Vega system

         USE_LANDOLT_REST = .FALSE.
         USE_LANDOLT_OBS  = .FALSE.

      IF ( UCOR_BXB .and. OPT_LANDOLT .EQ. 0 ) THEN
         USE_LANDOLT_REST = .TRUE.  ! color terms =0; but U -> U+BX-B
         MAG_PRIMARY = FILTREST_MAG_PRIMARY(IFILT_BESS_U)
         istat = landolt_ini( OPT_LANDOLT,
     &                        MAG_PRIMARY, LANDOLT_COLOR_SHIFT )

         CALL LANDOLT_SNMAG_CHECK(0, 0.0, 0.0)  ! Trest, AV
      ENDIF  ! end of OPT_LANDOLT option

c ----------------------------------------------
      IF ( OPT_LANDOLT .EQ. 0 ) RETURN
c ----------------------------------------------

      USE_LANDOLT_REST = BTEST(OPT_LANDOLT,0)  ! mask = 1
      USE_LANDOLT_OBS  = BTEST(OPT_LANDOLT,1)  ! mask = 2
      FORCE            = BTEST(OPT_LANDOLT,6)  ! mask = 64 -> FORCE use in SIM

      IF ( LSIM_SNANA .and. .NOT. FORCE ) THEN
          write(c1err,670) OPT_LANDOLT
670       format('OPT_LANDOLT=',I3,' is invalid for SIM.')
          c2err = 'Must set OPT_LANDOLT = 0 in &FITINP '
          CALL MADABORT(FNAM, c1err, c2err )
      ENDIF

c -----------------------------------------------
c if BX filter is not a survey filter,
c then add it to the SURVEY_FILTERS list and call RDKCOR again.


      LBX = IFILTDEF_INVMAP_SURVEY(ifilt_BESS_BX) .GT. 0

      IF ( USE_LANDOLT_OBS .and. .NOT. LBX ) THEN
         print*,' '
         print*,'    Add observer-frame X band to SURVEY filters ' //
     &               'for Landolt option'
         print*,' '
         call flush(6)
         SURVEY_FILTERS  = SURVEY_FILTERS(1:NFILTDEF_SURVEY) // 'X'
         NFILTDEF_SURVEY = NFILTDEF_SURVEY + 1
         i = NFILTDEF_SURVEY
         IFILTDEF_MAP_SURVEY(i) = IFILT_BESS_BX
         IFILTDEF_INVMAP_SURVEY(ifilt_BESS_BX) = i

         CALL READ_CALIB_WRAPPER(ISTAT)

         CALL CDTOPDIR_OUTPUT(STDOUT_UPDATE)  ! back to topdir (to be safe)

      ENDIF

c -----------------------------------
c make sure that BX filters is defined
      C2err =
     &   'Either set OPT_LANDOLT=0 or add BX filter to KCOR file.'

      IF ( USE_LANDOLT_OBS ) THEN
        IFILT = IFILTDEF_INVMAP_SURVEY(ifilt_BESS_BX)
        IF ( .NOT. EXIST_BXFILT_OBS .or. IFILT .LE. 0 ) THEN
            print*,' xxx IFILT, EXIST_BXFILT_OBS = ',
     &            IFILT, EXIST_BXFILT_OBS
          write(c1err,677) OPT_LANDOLT, 'OBS'
          CALL MADABORT(FNAM, c1err, c2err )
        ENDIF
      ENDIF
      IF ( USE_LANDOLT_REST ) THEN
         IFILT = IFILTDEF_INVMAP_REST(ifilt_BESS_BX)
         IF ( .not. EXIST_BXFILT_REST .or. IFILT .LE. 0) THEN
            write(c1err,677) OPT_LANDOLT, 'REST'
            print*,' xxx IFILT, EXIST_BXFILT_REST = ',
     &            IFILT, EXIST_BXFILT_REST
            CALL MADABORT(FNAM, c1err, c2err )
         ENDIF
      ENDIF

677      format('Cannot implement OPT_LANDOLT=',I3,
     &      ' without ', A,'-frame BX filter.')


       istat = landolt_ini( OPT_LANDOLT,
     &      FILTREST_MAG_PRIMARY(IFILT_BESS_U), LANDOLT_COLOR_SHIFT )


c check for VEGA or BD17 as reference;
c make crude sanity check on FILT_MAGPRIMARY to avoid
c mixing the wrong things.

      if ( BTEST(OPT_LANDOLT,2) ) then
         ctmp = 'VEGA'
      else
         ctmp = 'BD17'
      endif

      if ( USE_LANDOLT_REST ) then
           print*,'   Transform rest-Landolt => rest-Bessell',
     &             '  (', ctmp,')'
           call flush(6)
      endif

      if ( USE_LANDOLT_OBS ) then
           print*,'   Transform obs-Bessell => obs-Landolt ',
     &             '  (', ctmp,')'
           call flush(6)
      endif

      if ( USE_LANDOLT_REST ) then
        CALL LANDOLT_SNMAG_CHECK(0, 0.0, 0.0)  ! Trest, AV
      endif
      CALL LANDOLT_SNMAG_CHECK(1, 0.0, 0.0)
      CALL LANDOLT_SNMAG_CHECK(2, 0.0, 0.0)

      RETURN
      END

C =======================================
CDECK  ID>,  LANDOLT_CHECK. 
      SUBROUTINE LANDOLT_SNMAG_CHECK(OPT,Trest,AVwarp)
c
c Compute SN mags at t=0 for Bessell and Landolt;
c compare with external calculations.
c
c -----------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER OPT             ! () 0=>SN, 1=Vega, 2=BD17
      REAL    Trest, AVwarp   ! (I) test params

c local var

      INTEGER ifilt, OPT_CONVERT, istat

      REAL*8
     &   T8, Z8, AV8
     &  ,MAG8_BESS(MXFILT_ALL)     ! reported Bessell mags
     &  ,MAG8_SYNBESS(MXFILT_ALL)  ! synthetic Bessell
     &  ,MAG8_LAND(MXFILT_ALL)
     &  ,MAG8_INVERT(MXFILT_ALL)
     &  ,MAG8_BX, MAG8_B, MAG8_TMP

      character cflt*1

      REAL BD17_MAG_LANDOLT(MXFILT_ALL)
      REAL VEGA_MAG_LANDOLT(MXFILT_ALL)

c functions
      REAL*8 GET_MAGLC8, EVAL_KCOR_TABLE_LCMAG
      INTEGER LANDOLT_CONVERT

C --------------- BEGIN ---------------

      DO ifilt = 1, MXFILT_ALL
        MAG8_SYNBESS(ifilt) = -9.0
        MAG8_BESS(ifilt)    = -9.0
        MAG8_LAND(ifilt)    = -9.0
        MAG8_INVERT(ifilt)  = -9.0
      ENDDO

c hard-wire primary mags from John Marriner.

      BD17_MAG_LANDOLT(IFILT_BESS_U) = 9.724
      BD17_MAG_LANDOLT(IFILT_BESS_B) = 9.907
      BD17_MAG_LANDOLT(IFILT_BESS_V) = 9.464
      BD17_MAG_LANDOLT(IFILT_BESS_R) = 9.166
      BD17_MAG_LANDOLT(IFILT_BESS_I) = 8.846
      BD17_MAG_LANDOLT(IFILT_BESS_BX) = 9.907

      VEGA_MAG_LANDOLT(IFILT_BESS_U) = 0.011
      VEGA_MAG_LANDOLT(IFILT_BESS_B) = 0.015
      VEGA_MAG_LANDOLT(IFILT_BESS_V) = 0.017
      VEGA_MAG_LANDOLT(IFILT_BESS_R) = 0.024
      VEGA_MAG_LANDOLT(IFILT_BESS_I) = 0.020
      VEGA_MAG_LANDOLT(IFILT_BESS_BX) = 0.015

      print*,' '

      if ( OPT .EQ. 0 ) then
        print*,'  Check SN mags at Trest=',Trest,'  AVwarp=',AVwarp
        T8  = DBLE(Trest)
        AV8 = DBLE(AVwarp)
        Z8  = Zat10pc
        DO ifilt = IFILT_BESS_U, IFILT_BESS_BX
          MAG8_TMP = EVAL_KCOR_TABLE_LCMAG(ifilt,T8,Z8,AV8)
          MAG8_SYNBESS(ifilt) = MAG8_TMP - PEAKMAG_AT_10pc
        ENDDO
      ELSE IF ( OPT .EQ. 1 ) then
        print*,'  Check VEGA mags. '
        DO ifilt = IFILT_BESS_U, IFILT_BESS_BX
          MAG8_LAND(ifilt) = VEGA_MAG_LANDOLT(ifilt)
        ENDDO
        MAG8_LAND(IFILT_BESS_BX) =
     &  MAG8_LAND(IFILT_BESS_BX) - MAG8_LAND(IFILT_BESS_B)
        GOTO 400
      ELSE IF ( OPT .EQ. 2 ) then
        print*,'  Check BD17 mags. '
        DO ifilt = IFILT_BESS_U, IFILT_BESS_BX
          MAG8_LAND(ifilt) = BD17_MAG_LANDOLT(ifilt)
        ENDDO
        MAG8_LAND(IFILT_BESS_BX) =
     &  MAG8_LAND(IFILT_BESS_BX) - MAG8_LAND(IFILT_BESS_B)
        GOTO 400
      ELSE
        print*,' '
        print*,' LANDOLT_SNMAG_CHECK: UKNOWN OPT = ', OPT
        print*,' ***** ABORT ***** '
        STOP
      ENDIF


      OPT_CONVERT = +1
      istat = Landolt_convert(opt_convert
     &          ,MAG8_SYNBESS(IFILT_BESS_U)  ! input  UBVRI,X
     &          ,MAG8_LAND(IFILT_BESS_U)     ! output UBVRI
     &           )

c now invert to get back Bessell from Landolt.

      MAG8_BX = EVAL_KCOR_TABLE_LCMAG(ifilt_BESS_BX,T8,Z8,AV8)
      MAG8_B  = EVAL_KCOR_TABLE_LCMAG(ifilt_BESS_B, T8,Z8,AV8)

      MAG8_LAND(IFILT_BESS_BX) = MAG8_BX - MAG8_B

400   CONTINUE

      OPT_CONVERT = -1
      istat = Landolt_convert(opt_convert
     &          ,MAG8_LAND(IFILT_BESS_U)    ! input   land  UBVRI, BX-B
     &          ,MAG8_INVERT(IFILT_BESS_U)  ! output  synth UBVRI,X
     &           )

c convert synthetic mags into reported BESS mags.
      DO ifilt = IFILT_BESS_U, IFILT_BESS_BX
         MAG8_BESS(ifilt) = MAG8_INVERT(ifilt)
      ENDDO
      MAG8_BESS(ifilt_BESS_U) = MAG8_INVERT(ifilt_BESS_U)
     &                        - MAG8_INVERT(ifilt_BESS_BX)
     &                        + MAG8_INVERT(ifilt_BESS_B)

c --------

      print*,' '
      print*,'      synth      reported   syn-Bessell   Landolt->     '
      print*,'      Bessell    Bessell    -> Landolt    syn-Bessell   '
      print*,' ----------------------------------------------------- '

      DO ifilt = IFILT_BESS_U, IFILT_BESS_I
        cflt = FILTDEF_STRING(ifilt:ifilt)
        write(6,20)  cflt
     &    ,MAG8_SYNBESS(ifilt)
     &    ,MAG8_BESS(ifilt)
     &    ,MAG8_LAND(ifilt)
     &    ,MAG8_INVERT(ifilt)

20      format(T3,A, 2x,4(F9.4,3x) )

      ENDDO

      print*,' ----------------------------------------------------- '
      CALL FLUSH(6)

      RETURN
      END

C ====================================
CDECK  ID>,  SETFILTOBS. 
      SUBROUTINE SET_IFILT_OBS(LPRINT)
c
c Sets up appropriate observer-filter ranges before fit begins
c so that USRFUN need not compute filter ranges during each
c call.
c
c Set the following FILTCOM varaibles for this SN:
c   IFILT_OBS_EVAL_MASK(ifilt_obs)  => mask of obs filters to evaluate
c
c  Example: U-band needs to evaluate obs U,B,V,BX
c   => IFILT_OBS_EVAL_MASK(IFILT_BESS_U) = bits 6,7,8,11
c
c
c Apr 22 2022: pass LPRINT logical flag as input argument
c --------------------------------------

      IMPLICIT NONE

      LOGICAL  LPRINT  ! (I)


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID


c +CDE,SNANAFIT.  from snana.car

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      INTEGER
     &   ifilt, ifilt2
     &  ,ifilt_obs, ifilt2_obs
     &  ,LL, NFUSE

      INTEGER*8 MSKTMP8(2)

      LOGICAL LBESS_OBS, LTMP, MULTIFILT, USE
      character cfilt*2, cfilt2*2

c functions
      LOGICAL FILTBTEST

C -------------- BEGIN --------------

      LL = ISNLC_LENCCID

      DO ifilt = 1, MXFILT_ALL
        IFILT_OBS_EVAL_MASK(1,ifilt) = 0
        IFILT_OBS_EVAL_MASK(2,ifilt) = 0
      ENDDO

c check if any of the OBS filters are in the Bessell90 system
      LBESS_OBS = .FALSE.
      DO ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         if ( ifilt_obs .GE. IFILT_BESS_U .and.
     &        ifilt_obs .LE. IFILT_BESS_I ) LBESS_OBS = .TRUE.
      ENDDO

c set default mask to evaluate only observer filter
c (ie.. no color transformations).

      MULTIFILT = .FALSE.

      DO ifilt = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         USE = USE_FILT(ifilt_obs) .or. LFILTDEF_NONSURVEY(ifilt_obs)
         if ( USE ) then
            CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,ifilt_obs),
     &                   ifilt_obs)
        endif
      ENDDO

c -----------------------------------------------------
c check option to correct U with BX-B
c Note that UCOR is used automatically with OPT_LANDOLT;
c this is to allow UCOR_BXB without the LANDOLT option

      IF ( UCOR_BXB .and. LBESS_OBS ) THEN

         MULTIFILT = .TRUE.

         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_U)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_B)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_BX)

      ENDIF

c -----------------------------------------------------
c check options that involve color transformations.

      IF ( USE_LANDOLT_OBS .and. LBESS_OBS ) THEN

         MULTIFILT = .TRUE.

c --- U
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_U)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_B)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_V)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_U),
     &                IFILT_BESS_BX)

c --- B

         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_B),
     &                IFILT_BESS_B)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_B),
     &                IFILT_BESS_V)

c --- V
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_V),
     &                IFILT_BESS_B)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_V),
     &                IFILT_BESS_V)

c --- R
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_R),
     &                IFILT_BESS_B)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_R),
     &                IFILT_BESS_V)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_R),
     &                IFILT_BESS_R)

c --- I
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_I),
     &                IFILT_BESS_B)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_I),
     &                IFILT_BESS_V)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_I),
     &                IFILT_BESS_R)
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_I),
     &                IFILT_BESS_I)

c --- BX
         CALL FILTBSET(IFILT_OBS_EVAL_MASK(1,IFILT_BESS_BX),
     &                IFILT_BESS_BX)

      ENDIF

c ----------
c write list of filters to fit
c
      NFUSE = INDEX(FILTLIST_FIT_USE,' ') - 1

      IF ( LPRINT ) THEN
        write(6,44) SNLC_CCID(1:LL), FILTLIST_FIT_USE(1:NFUSE)
44      format(T5,'CID ',A,' : FIT OBSERVER FILTERS ', A )
      ENDIF
c ----------------------------------------
c  print obs filters for each filter when mutliple filters
c  are needed per band, such as for the Landolt correction

      LTMP = (N_SNLC_FITCUTS .LT. 20) .and. MULTIFILT

      IF ( LTMP ) THEN
        if ( LPRINT ) print*,' '

        DO 29 ifilt = 1, NFILTDEF_SURVEY

         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         USE = USE_FILT(ifilt_obs)
         if ( .NOT. USE ) goto 29

         cfilt  = filtdef_string(ifilt_obs:ifilt_obs)
         MSKTMP8(1) = IFILT_OBS_EVAL_MASK(1,ifilt_obs)
         MSKTMP8(2) = IFILT_OBS_EVAL_MASK(2,ifilt_obs)

         write(6,20) SNLC_CCID(1:LL), cfilt
20       format(T10,'SN ',A,': OBSERVER-',A1,' => evaluate obs ', $)

         DO ifilt2 = 1, NFILTDEF_SURVEY
            ifilt2_obs = IFILTDEF_MAP_SURVEY(ifilt2)
            cfilt2 = filtdef_string(ifilt2_obs:ifilt2_obs)
            LTMP = FILTBTEST(MSKTMP8,ifilt2_obs)
            if ( LTMP .and. LPRINT ) write(6,21) cfilt2(1:1)
21          format(A1, $)
         ENDDO
         if ( LPRINT ) print*, '  (ifilt=', ifilt, ')'

29      CONTINUE ! end of IFILT loop

      ENDIF    ! end of LTMP if-block

      RETURN
      END     ! end SET_IFILT_OBS


C ===================================
CDECK  ID>,  INIFUDGE. 
      SUBROUTINE INIT_FUDGE_FITERR
c
c Created Jul 18, 2008
c (code moved from FITPAR_INI)
c
c Feb 19 2010: abort if MAXFRAC>0, but TREST-range or LAM-range
c              is zero.
c
c Mar 1 2017: do NOT return after FUDGEALL_MAXFRAC -->
c             allow mixing with other options.
c ---------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER LL, ifilt, ifilt_obs

      character ctmp*4

      INTEGER FILTINDX

C ------------- BEGIN ------------

      USE_FUDGE_FITERR = .FALSE.

      IF ( FUDGE_MAGERR_MODEL .GE. 0.0 ) THEN
         write(6,16) FUDGE_MAGERR_MODEL
16       format(T5,'FIT-MODEL FUDGE WARNING: ',
     &       ' ALL MODEL-MAG ERRORS -> ', F6.3,' mag ' )
      ENDIF

      IF ( FUDGEALL_MAXFRAC .GT. 0.0 ) THEN
        write(6,179) FUDGEALL_MAXFRAC
179     format(T5,'FIT-ERROR fudge = ', F6.2,' * max(Flux)', 3x,
     &    'for all epochs and fit-iterations.' )
       USE_FUDGE_FITERR = .TRUE.
      ENDIF

      IF ( FUDGEALL_ITER1_MAXFRAC .GT. 0.0 ) THEN
         write(6,79) FUDGEALL_ITER1_MAXFRAC, 1
         USE_FUDGE_FITERR = .TRUE.
      ENDIF

      IF ( FUDGE_FITERR_PASSBANDS .EQ. 'NULL' ) RETURN
      IF ( FUDGE_FITERR_MAXFRAC   .EQ. 0.     ) RETURN

      USE_FUDGE_FITERR = .TRUE.

      LL = INDEX ( FUDGE_FITERR_PASSBANDS, ' ' ) -  1

      DO ifilt     = 1, LL
         ctmp      = FUDGE_FITERR_PASSBANDS(ifilt:ifilt)
         ifilt_obs = FILTINDX(ctmp)
         DOFUDGE_FITERR(ifilt_obs) = .TRUE.

         write(6,77) ctmp(1:1),
     &         FUDGE_FITERR_TREST(1), FUDGE_FITERR_TREST(2)

77       format(T5,'Fudge ',A,'-band FIT-ERRORS for ',
     &          F6.1, ' < Trest < ', F6.1,' days ' )

         if ( FUDGE_FITERR_TREST(3) .LT. 900. ) then
             write(6,77) ctmp(1:1),
     &         FUDGE_FITERR_TREST(3), FUDGE_FITERR_TREST(4)
         endif

         write(6,78) int(FUDGE_FITERR_RESTLAM(1))
     &              ,int(FUDGE_FITERR_RESTLAM(2))

         if( FUDGE_FITERR_RESTLAM(3) .LT. 80000. ) then
           write(6,78)  int(FUDGE_FITERR_RESTLAM(3))
     &                 ,int(FUDGE_FITERR_RESTLAM(4))
         endif

78       format(T30,'and ', I5,' < RESTLAM < ', I5,' Angstroms')

      ENDDO

      write(6,79) FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_MAXITER
79    format(T5,'FIT-ERROR fudge = ', F6.2,' * max(Flux)', 3x,
     &    'for ITER <=',I2   )
      print*,'  '


c ----------------------------------------------------
c sanity checks to prevent setting bad FUDGEs

      write(c1err,661) FUDGE_FITERR_MAXFRAC
661   format('FUDGE_FITERR_MAXFRAC = ',F8.2)

      IF ( FUDGE_FITERR_TREST(1) .GE. FUDGE_FITERR_TREST(2) ) then
         c2err = 'but  FUDGE_FITERR_TREST  is not set.'
         CALL MADABORT("INIT_FUDGE_FITERR", c1err, c2err)
      ENDIF
      IF ( FUDGE_FITERR_RESTLAM(1).GE.FUDGE_FITERR_RESTLAM(2)) then
         c2err = 'but  FUDGE_FITERR_RESTLAM  is not set.'
         CALL MADABORT("INIT_FUDGE_FITERR", c1err, c2err)
      ENDIF

      RETURN
      END

C ==========================================
CDECK  ID>,  DMP_DICTFILE. 
      SUBROUTINE DMP_DICTFILE(IFLAG)
c
c Created Apr 13, 2009 by R.Kessler
c
c Write SALT2 results to "dictFile" ...
c the particular format needed by their
c "hubblefit" program. Note that SNANA does
c NOT use this DICTFILE for anything;
c this is just a convenience option to
c use the original SALT2 hubblefit with
c the output of snlc_fit.exe
c
c IFLAG = 0 => open file; write header
c IFLAG > 0 => update with next SN

c ------------------

      IMPLICIT NONE

C +CDE,SNDATCOM.  from snana.car inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.  from snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )






      INTEGER IFLAG ! (I) 0-> open file; 1-> write

c local

      INTEGER LTMP,  ivar

      INTEGER NVAR_DICTFILE
      PARAMETER ( NVAR_DICTFILE =  17 )
      REAL*8  XVAR(NVAR_DICTFILE)

C ----------- BEGIN ----------

      IF ( FITMODEL_INDEX .NE. MODEL_SALT2 ) RETURN

      IF ( IFLAG .EQ. 0 ) THEN

c init dictFile and  write header

        OPEN(UNIT= LUNSALT2, FILE = SALT2_DICTFILE,
     &         STATUS='UNKNOWN', ERR=92)

        write(6,90) SALT2_DICTFILE(1:LTMP)
90      format(T5,'Open SALT2 DICT-FILE : ', A)
        print*,' '

c write mandatory header
        write(LUNSALT2,20) 'z',  1,'redshift'
        write(LUNSALT2,20) 'X0', 2,'10^[-0.4*(mu + alpha*x1 - beta*c)]'
        write(LUNSALT2,20) 'X0e',3,'error on x_0'
        write(LUNSALT2,20) 'X1', 4,'stretch/luminosity parameter'
        write(LUNSALT2,20) 'X1e',5,'error on x_1'
        write(LUNSALT2,20) 'X2', 6,'bidon'
        write(LUNSALT2,20) 'X2e',7,'bidon'
        write(LUNSALT2,20) 'X3', 8,'color'
        write(LUNSALT2,20) 'X3e',9,'error on color'
        write(LUNSALT2,20) 'msb',10,'reference B-mag'
        write(LUNSALT2,20) 'msbe',11,'error on above'

        write(LUNSALT2,20) 'X0X1_c', 12, 'x_0/x_1 Correlation'
        write(LUNSALT2,20) 'X0X2_c', 13, 'bidon'
        write(LUNSALT2,20) 'X0X3_c', 14, 'x_0/color Correlation'
        write(LUNSALT2,20) 'X1X2_c', 15, 'bidon'
        write(LUNSALT2,20) 'X1X3_c', 16, 'x_1/color Correlation'
        write(LUNSALT2,20) 'X2X3_c', 17, 'bidon'
        write(LUNSALT2,20) 'end'

20      format('#', A, T9,': (', I2.2,') ', A)

        RETURN

      ENDIF  ! end if IFLAG=0


c --------------

      ivar = 0

      IVAR = IVAR + 1
      XVAR(ivar) = SNLC_ZCMB

c x0
      IVAR = IVAR + 1
      XVAR(ivar) = LCVAL_STORE(IPAR_X0)
      IVAR = IVAR + 1
      XVAR(ivar) = LCERR_STORE(IPAR_X0)

c x1
      IVAR = IVAR + 1
      XVAR(ivar) = LCVAL_STORE(IPAR_SHAPE)
      IVAR = IVAR + 1
      XVAR(ivar) = LCERR_STORE(IPAR_SHAPE)

c x2
      IVAR = IVAR + 1
      XVAR(ivar) = 0.0
      IVAR = IVAR + 1
      XVAR(ivar) = 0.0

c x3 = color
      IVAR = IVAR + 1
      XVAR(ivar) = LCVAL_STORE(IPAR_COLOR)
      IVAR = IVAR + 1
      XVAR(ivar) = LCERR_STORE(IPAR_COLOR)

c mB*
      IVAR = IVAR + 1
      XVAR(ivar) = LCVAL_STORE(IPAR_MB)
      IVAR = IVAR + 1
      XVAR(ivar) = LCERR_STORE(IPAR_MB)

c now the covariances ...

c #X0X1_c :
      IVAR = IVAR + 1
      XVAR(ivar) = FITERRMAT(IPAR_X0,IPAR_SHAPE)

c #X0X2_c :  bidon
      IVAR = IVAR + 1
      XVAR(ivar) = 0.0

c #X0X3_c :  x0-color cov
      IVAR = IVAR + 1
      XVAR(ivar) = FITERRMAT(IPAR_X0,IPAR_COLOR)

c #X1X2_c :   bidon
      IVAR = IVAR + 1
      XVAR(ivar) = 0.0

c #X1X3_c :   x1-color cov
      IVAR = IVAR + 1
      XVAR(ivar) = FITERRMAT(IPAR_SHAPE,IPAR_COLOR)

c #X2X3_c : bidon
      IVAR = IVAR + 1
      XVAR(ivar) = 0.0

c -----------------------

c  write XVAR
      DO ivar = 1, NVAR_DICTFILE
        write(LUNSALT2, '(G14.6,$)' ) XVAR(ivar)
      END DO
      write(LUNSALT2, '(A)') ' '
      CALL FLUSH(LUNSALT2)

      GOTO 888

c ---------------------
92    CONTINUE
      c1err = 'Could not open SALT2_DICTFILE: '
      c2err = SALT2_DICTFILE
      CALL MADABORT("DMP_DICTFILE", c1err, c2err)

888   CONTINUE
      RETURN
      END


C =======================================
CDECK  ID>,  DMP_COVAR. 
      SUBROUTINE DMP_COVAR(iter)
c
c Created Jun 2, 2011 by R.Kessler
c
c Dump non-zero elements of COVMAT2 matrix
c before it is  inverted.
c
      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

      INTEGER iter  ! (I) fit-iteration to prepare
c local variables

      INTEGER NDMP, IROW, ICOL, IFILT_ROW, IFILT_COL
      INTEGER ep_row, ep_col
      REAL*8  COVTMP8

      character cfilt_row*2, cfilt_col*2

C ---------------- BEGIN ------------

       print*,' --------------------------------------- '
       print*,' COVMAT DUMP for CID=', SNLC_CCID,
     &      '   FIT-ITER=', ITER

       NDMP = 0

       DO 301 irow = 1, NFITDATA
       DO 302 icol = 1, NFITDATA

         COVTMP8     = COVMAT2(irow,icol)
         if ( COVTMP8 .EQ. 0.0 ) GOTO 302

         ep_row = EPLIST_FIT(irow)
         ep_col = EPLIST_FIT(icol)

         NDMP = NDMP + 1
         IFILT_ROW   = I4EP_ALL(ep_row,IEP_IFILT_OBS)
         IFILT_COL   = I4EP_ALL(ep_col,IEP_IFILT_OBS)
         cfilt_row   = FILTDEF_STRING(ifilt_row:ifilt_row)
         cfilt_col   = FILTDEF_STRING(ifilt_col:ifilt_col)

         write(6,660)
     &      R4EP_ALL(ep_row,JEP_TREST), cfilt_row,
     &      R4EP_ALL(ep_col,JEP_TREST), cfilt_col,
     &      COVTMP8,
     &      R8EP_MJD(irow), R8EP_MJD(icol)
660      format(T3,'COVMAT[ ', F6.2, '(', A1, ')'  ,
     &          F6.2, '(', A1, ') ] = ', F15.6 ,
     &          4x,'MJD=', F9.3,','F9.3
     &     )

302    CONTINUE
301    CONTINUE

      write(6,661) NFITDATA,  NFITDATA, NFITDATA*NFITDATA
661   format(T3,'COVMAT FULL-SIZE: ', I4,' x ', I4, ' = ', I8)

      write(6,662) NDMP
662   format(T3,'COVMAT Number of non-zero elements: ', I8)

      RETURN
      END

C ========================================
CDECK  ID>,  DMPSNMJD. 
      SUBROUTINE DMP_SNMJD_INTERP(IFLAG,OPTMJD)
c
c For specified MJDs, write MAG(obs & rest) , FLUX & KCOR
c to special dump file. List has been read from
c SNMJD_LIST_FILE. Output file has same name as input,
c but with .OUT extension.
c
c March 24, 2008:
c       Add OPTMJD (see below)
c
c May 28, 2008: fix dumb bug so that PEAKMJD dump happens only once.
c
c May 18, 2012: use new GET_INTERP_MJDLIST utility
c Aug 15, 2012: protect printing info for undefined IFILT_OBS.
c
c Jul 31 2015: write fitres [column] format to make it easier to parse.
c
c Nov 19 2019: remove NVAR key
c Dec 04 2019: remove obsolete IFILTOBS_RST to avoid negative index
c
c ------------

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,INTERPCM. inserted below by ypatchy. 

c arrays for interpolation

      INTEGER MXINTERP
      PARAMETER ( MXINTERP = 1000) ! ->1000 Nov 19 2019 (was 100)

      INTEGER*4
     &   N_INTERP_MJDLIST        ! # SN MJDs to interpolate

      REAL*8
     &   INTERP8_MJDLIST(MXINTERP)

      CHARACTER
     &   INTERP_CCIDLIST(MXINTERP)*(MXCHAR_CCID)

      INTEGER N_INTERP_MJDLIST_DONE
      LOGICAL INTERP_MJDLIST_DONE(MXINTERP)

      COMMON / SNMJD_INTERPCOM /
     &    N_INTERP_MJDLIST, INTERP_CCIDLIST
     &   ,INTERP_MJDLIST_DONE, N_INTERP_MJDLIST_DONE

      COMMON / SNMJD_INTERPCOM8 / INTERP8_MJDLIST


c IFLAG = 0 => open output file
c IFLAG > 0 => update file with SN if MJD is specified
c IFLAG < 0 => close file.

      INTEGER
     &   IFLAG      ! (I) SN sparse index
     &  ,OPTMJD     ! (I) 0=>use PEAKMJD, 1=> use MJD from file.

c local args

      INTEGER
     &   LTMP, imjd, NMJD, ipar, NVAR_OUT
     &  ,CID, CID_TMP
     &  ,IFILT, IFILT_OBS, IFILT_RST

      REAL*8
     &   MJD8, MJD8_LAST, MJD8LIST(MXINTERP)
     &  ,FLUX8, FLUX8ERR
     &  ,MAG8, MAG8ERR, KCOR8

      REAL
     &    TOBS, TREST, PKMJD
     &   ,FLUXOBS_INTERP(MXFILT_ALL)
     &   ,FLUXERROBS_INTERP(MXFILT_ALL)
     &   ,MAGOBS_INTERP(MXFILT_ALL)
     &   ,MAGERROBS_INTERP(MXFILT_ALL)
     &   ,KCOR_INTERP(MXFILT_ALL)
     &   ,MAGRST_INTERP(MXFILT_ALL)  ! model mags
     &   ,MAGERRRST_INTERP(MXFILT_ALL)  ! model mags
     &   ,MAGRST2_INTERP(MXFILT_ALL) ! training mags
     &   ,MAGERRRST2_INTERP(MXFILT_ALL) ! training mags
     &   ,VAL, ERR

      CHARACTER CCID*(MXCHAR_CCID), BAND*2

      LOGICAL LDMP, LSKIP, ADDFLAG

      PARAMETER ( NVAR_OUT=9 )

C ------------ BEGIN -----------

c negative IFLAG => end of program
      IF ( IFLAG < 0 ) THEN
        CLOSE ( UNIT = LUNINTERP  )
        RETURN
      ENDIF

      PKMJD = LCVAL_STORE(IPAR_PEAKMJD) + MJDOFF

c open output file.
      IF ( IFLAG .EQ. 0 ) THEN

        GLOBAL_BANNER = "OPEN TEXT-FILE TO DUMP INTERPOLATED MAGS"
        CALL PRBANNER (GLOBAL_BANNER )

        LTMP = INDEX ( SNMJD_LIST_FILE, ' ' ) - 1

        if ( SNMJD_OUT_FILE .EQ. ' ' ) then
          SNMJD_OUT_FILE = SNMJD_LIST_FILE(1:LTMP) // '.OUT'
        endif

        LTMP = INDEX ( SNMJD_OUT_FILE, ' ' ) - 1
        OPEN(UNIT= LUNINTERP, FILE=SNMJD_OUT_FILE,
     &         STATUS='UNKNOWN', ERR=92)

        write(6,90) SNMJD_OUT_FILE(1:LTMP)
90      format(T5,'Open MAG-interp file : ', A)
        print*,' '

        WRITE(LUNINTERP,40) 'Interpolation Results at MJD_INTERP'
        WRITE(LUNINTERP,402)
402     FORMAT('VARNAMES: CID BAND MJD_INTERP MAG MAGERR '
     &                   'FLUX FLUXERR TOBS TREST' )

        RETURN

      ENDIF  ! end of IFLAG = 0 block

c ----------------------------------
c search MJD(s) for this SN:

      CCID = SNLC_CCID
      CALL GET_INTERP_MJDLIST(CCID, NMJD, MJD8LIST, ADDFLAG)

      MJD8_LAST = -9.0

      DO 200 imjd = 1, NMJD

        IF ( OPTMJD .EQ. 1 ) THEN
           MJD8 = MJD8LIST(imjd)
        ELSE
           MJD8 = PKMJD
        endif

c avoid repeating an MJD ... mainly to avoid multiple PEAKMJD entries.
        IF ( MJD8 .EQ. MJD8_LAST ) GOTO 200


c get observer mags,flux,kcor at this MJD

        DO IFILT = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)

          if ( USE_FILT(ifilt_obs) ) then

             CALL MODELMAG_CALC(ifilt_obs, 'OBS', MJD8,
     &           FLUX8, FLUX8ERR, MAG8, MAG8ERR, KCOR8 ) ! return args

             FLUXOBS_INTERP(ifilt_obs)    = FLUX8
             FLUXERROBS_INTERP(ifilt_obs) = FLUX8ERR
             MAGOBS_INTERP(ifilt_obs)     = MAG8
             MAGERROBS_INTERP(ifilt_obs)  = MAG8ERR
             KCOR_INTERP(ifilt_obs)       = KCOR8

          endif
        ENDDO
c -------------------------
c write results to output file.

        TOBS = MJD8 - PKMJD
        TREST = TOBS / ( 1.0 + REDSHIFT_FIT )

        if ( MJD8 < 1.0 ) GOTO 4000

        write(LUNINTERP,40) ' '
40      format('# ', A)
        DO 1400 IFILT = 1, NFILTDEF_SURVEY
          ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
          BAND      = FILTDEF_STRING(ifilt_obs:ifilt_obs)
          if ( .not. USE_FILT(ifilt_obs) ) GOTO 1400


           write(LUNINTERP,405)
     &       CCID(1:ISNLC_LENCCID),
     &       BAND, MJD8,
     &       MAGOBS_INTERP(ifilt_obs),  MAGERROBS_INTERP(ifilt_obs),
     &       FLUXOBS_INTERP(ifilt_obs), FLUXERROBS_INTERP(ifilt_obs),
     &       TOBS, TREST

405        format('INTERP: ',
     &          A, 1x, A1, 1x, F9.3,   ! CCID, BAND, MJD8
     &          2x, 2F7.3,               ! MAG MAGERR
     &          2x, 2G10.4,              ! FLUX FLUXERR
     &          2F7.2                    ! TOBS TREST
     &             )

1400    CONTINUE

        MJD8_LAST = MJD8

200   CONTINUE  ! end of main SNMJD loop

      IF( OPTMJD > 0 ) GOTO 6000

c --------------------

4000  CONTINUE

c Write out the fit parameters
c Make sure to write out PEAKMJD even if it's fixed.

      LTMP = INDEX(FITMODEL_VERSION,' ') - 1
      write(LUNINTERP,410)
     &    FITMODEL_VERSION(1:LTMP), CCID(1:ISNLC_LENCCID)
410   format(/,T4,A,' FIT-PARAMETERS for ',A, ': ' )

      DO 400 ipar = 1, NFITPAR_MN

         LDMP = FLOATPAR(ipar)
     &     .or. IPAR.EQ. IPAR_PEAKMJD
     &     .or. IPAR.EQ. IPAR_zPHOT

         if ( .not. LDMP ) goto 400

         VAL = FITVAL_STORE(ipar)
         ERR = FITERR_STORE(ipar)

         if ( IPAR .EQ. IPAR_PEAKMJD ) VAL = VAL + MJDOFF

         LTMP = INDEX ( PARNAME_STORE(ipar), ' ' ) - 1
         write(LUNINTERP,420) PARNAME_STORE(ipar)(1:LTMP), VAL, ERR

420      format(T10,A,'= ', T20, G12.3, ' +- ', G10.3 )

400   CONTINUE
      write(LUNINTERP,40)
     &  '========================================================='
c ---------------------------

6000  CONTINUE
      CALL FLUSH(LUNINTERP)
      RETURN

c ----------------------------------
92    CONTINUE
      c1err = 'Could not open MAG-INTERP output file '
      c2err = SNMJD_OUT_FILE
      CALL MADABORT("DMP_SNMJD_INTERP", c1err, c2err)

      RETURN
      END


C ===============================
CDECK  ID>,  PREPTUP. 
      SUBROUTINE PREP_FITRES_TABLEVAR()

c Created Sep 2012 by R.Kessler
c Prepare some FITRES table variables.
c
c Apr 29, 2013: fill CWNT_COV
c May 14 2014: overhaual using keep, TABLEVARCOM.
c
c
      IMPLICIT NONE

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------
c+CDE,CWNTCOM.

      INTEGER
     &   i, i2, ifilt, ifilt_obs, ifilt_obs2
     &  ,iep, ipar, ipar1, ipar2, ICOV, ITER

      character
     &   cfilt1*2, cfilt2*2
     &  ,cfilt1_lower*2, cfilt2_lower*2

      LOGICAL LF2, NONSURVEY
      REAL RHO, COV

      REAL*8 PKMJD8, XTMW

C --------------- BEGIN -------------

      ITER    = NFIT_ITERATION
      PKMJD8  = FITVAL(IPAR_PEAKMJD,ITER)
      CALL LOAD_EPALL(ITER,PKMJD8)

c ----------------------------------
c load MINUIT reduced correlation matrix into linear array

      do ipar = 1, MXCOV_TBL
         TBL_COV(ipar)    = -999.
         TBL_REDCOV(ipar) = -999.
      enddo

      DO 100 ICOV = 1, NCOV_TBL

         IPAR1 = IPAR_TBL_COV(1,ICOV)
         IPAR2 = IPAR_TBL_COV(2,ICOV)

         if ( NGRID_PDF .LE. 0 ) then
            RHO = FITCORMAT(ipar1,ipar2)
            COV = FITERRMAT(ipar1,ipar2)
         else
            RHO = PDFCORMAT(ipar1,ipar2)
            COV = PDFERRMAT(ipar1,ipar2)
         endif

         TBL_COV(ICOV)    = COV
         TBL_REDCOV(ICOV) = RHO

 100  CONTINUE


c fill SNRMAX and XTMW arrays with only fitted bands.

      DO ifilt     = 1, NFILTDEF_SURVEY
         TBL_XTMW(ifilt)   = -999.
         TBL_SNRMAX(ifilt) = -999.
      ENDDO

      DO 200 i     = 1, NFILTOBS_TABLE
         ifilt_obs = IFILTOBS_MAP_TABLE(i)
         ifilt     = IFILT_MAP_TABLE(i)

         if ( use_filt(ifilt_obs) ) then
            iep   = I4BAND_EP_NEARPEAK(ifilt_obs)

            NONSURVEY = LFILTDEF_NONSURVEY(ifilt_obs)
            if ( NONSURVEY ) iep = 1 ! avoid -9999 index

c           print*,' xxx iep,ifilt, ifiltobs = ', iep, ifilt, ifilt_obs

            if ( iep > 0 ) then
               XTMW          = R4EP_ALL(iep,JEP_MWXT)  ! mag
               TBL_XTMW(i)   = 10**(-0.4*XTMW)         ! flux-frac
               TBL_SNRMAX(i) = R4BAND_SNRMAX_FIT(ifilt)
            endif
         endif
200   CONTINUE

      RETURN
      END    ! end of PREP_FITRES_TABLEVAR


C ========================================
CDECK  ID>,  TEST_TRANSFORM. 
      SUBROUTINE TEST_TRANSFORM(Z4)
c
c Test rest->observer frame transformation.
c For well-defined filter set, this transformation
c is simply a K-correction on a warped spectrum.
c For John's color transformation, it's a little more
c complicated.
c

      IMPLICIT NONE

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------


      REAL*4  Z4  ! (I) redshift

c  local args

      REAL*4  LMIN4

      INTEGER
     &   ifilt_obs
     &  ,ifilt_rest1
     &  ,ifilt_rest2
     &  ,OPT

      REAL*8
     &   T8, Z8, FLux8, MAG8
     &  ,DELTA8(2), AV8, MWEBV8, DLMAG8
     &  ,AVwarp8, KCOR8(2), XTAV, XTMW,MAGERR8, RVMW8

      LOGICAL LDMP / .FALSE. /

c functions
      REAL*8 USRFUN
      INTEGER NEAREST_IFILTDEF_WRAPPER

c -------------- BEGIN ------------

      CALL PRBANNER("TEST REST -> OBSERVER TRANSFORMATION")

      Z8     = DBLE(Z4)

      T8        = ZERO8
      DELTA8(1) = ZERO8
      DELTA8(2) = ZERO8
      AV8       = INIVAL_AV
      MWEBV8    = ZERO8
      RVMW8     = DBLE(RV_MWCOLORLAW)
      DLMAG8    = ZERO8


      print*,' Z=',Z4,'  Trest=',sngl(T8),'   AV=',sngl(AV8)
      print*,' MWE(B-V)=', sngl(MWEBV8), '   DLMAG=',sngl(DLMAG8)

      print*,' IFILTDEF_MAP_SURVEY = ', IFILTDEF_MAP_SURVEY

c      write(6,18) MAG_REST_TEST
c18    format(T3,'REST UBVRI mags: ', 5F8.4 )

      print*,' '

      DO ifilt_obs = 1,10

         OPT = OPT_FILTOBS
         ifilt_rest1 = NEAREST_IFILTDEF_WRAPPER(opt,ifilt_obs,
     &                      1, Z4, LMIN4 )
         ifilt_rest2 = NEAREST_IFILTDEF_WRAPPER(opt,ifilt_obs,
     &                      2, Z4, LMIN4 )

         FLUX8 =
     &     USRFUN ( NFIT_ITERATION, ifilt_obs, Z8, T8
     &             ,DELTA8, DLMAG8, AV8, RVMW8, MWEBV8, LDMP
     &             ,AVwarp8, KCOR8, XTAV, XTMW, MAGERR8 )    ! (O)

ccc         MAG8 = -2.5*DLOG10(FLUX8/ADUSCALE)
         MAG8 = -2.5*DLOG10(FLUX8) + ZEROPOINT_FLUXCAL_DEFAULT

         write(6,20)
     &     filtdef_string(ifilt_obs:ifilt_obs), MAG8
     &    ,filtdef_string(ifilt_rest1:ifilt_rest1)
     &    ,filtdef_string(ifilt_rest2:ifilt_rest2)
     &    ,AVwarp8, KCOR8(1)

 20      format(T5,'obsMag(',A,')=',F8.4, 3x,
     &             'AVwarp(',A,'-',A,')=', F7.3 , 3x,
     &             'Kcor=',F7.3
     &         )

      ENDDO

c -------------------------------

      RETURN
      END

C ===========================
CDECK  ID>,  SNLCPLOT. 
      SUBROUTINE SNLCPLOT()

c ---------------------------------------------
c Created Feb 2013 by R.Kessler
c
c Pack light curve & best-fit function for snlc_fit.exe.
c Also pack optional info such as marginalized distributions.
c
c Jul 19, 2013: add MJD list to SNLCPAK_DATA
c Jan 25, 2014: use new I4EP_FIT and R4EP_FIT arrays.
c Dec 10, 2017: fix to work with SNTABLE_FILTER_REMAP
c Jan 23, 2020: pack KCOR and AVWARP for rest-frame model
c ---------------------------------------------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.    public snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.    fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      INTEGER MXEP_SNLCPAK   !  includes all filters
      PARAMETER ( MXEP_SNLCPAK = 10*MXEPOCH )

      CHARACTER  CCID*(MXCHAR_CCID)

      REAL*8
     &   VMJD(MXEP_SNLCPAK)
     &  ,VTOBS(MXEP_SNLCPAK)
     &  ,VFLUXOBS(MXEP_SNLCPAK)
     &  ,VFLUXOBS_ERR(MXEP_SNLCPAK)
     &  ,VFLUXREST(MXEP_SNLCPAK)  ! K-corrected rest-frame flux
     &  ,VKCOR(MXEP_SNLCPAK)
     &  ,VAVWARP(MXEP_SNLCPAK)
     &  ,VSIMFLUXREST(MXEP_SNLCPAK)
     &  ,VSIMFLUXOBS(MXEP_SNLCPAK)   ! May 20 2016
     &  ,VZERO(MXEP_SNLCPAK)         ! zeros for true simFlux error
     &  ,VCHI2(MXEP_SNLCPAK)
     &  ,VREJECT(MXEP_SNLCPAK)
     &  ,VDUMERR(MXEP_SNLCPAK)  ! all zeros
     &  ,VBAND_NDOF(MXFILT_OBS)
     &  ,VBAND_CHI2(MXFILT_OBS)
     &  ,VBAND_PKFLUX(MXFILT_OBS)
     &  ,VBAND_PKFLUX_ERR(MXFILT_OBS)
     &  ,VBAND_PKMJD(MXFILT_OBS)
     &  ,VBAND_PKMJD_ERR(MXFILT_OBS)
c
     &  ,FLUX, COR, FPEAK, FPERR, PKMJD
     &  ,TMIN, TMAX, TBIN, xi, TOBS

      INTEGER
     &   LENCCID, NOBS, i, ifilt, ifilt_obs, NFILT, NBT, indxR4
     &  ,NFILTARG, IFILTARG, IFILTARG_MAP_SURVEY(MXFILT_ALL), NDOF
     &  ,IFILTOBS_REMAP, IFILT_REMAP_TMP
     &  ,VFILTOBS(MXEP_SNLCPAK)
     &  ,VFILTREST(MXEP_SNLCPAK)

      LOGICAL DO_RESTFLUX

c functions
      REAL*8 GET_FLUX_FITFUN
      LOGICAL DOPLOT_SNLC

C -------------------- BEGIN ---------------

c check if plot should be made
      IF ( .NOT. DOPLOT_SNLC() ) RETURN

      LENCCID = ISNLC_LENCCID
      CCID = SNLC_CCID(1:LENCCID) // char(0)
      NFILT = NFILTDEF_SURVEY

      write(6,10) SNLC_CCID(1:LENCCID)
 10   format(T10,'SNLCPAK: pack CID = ',A,' for plotting.')
      call flush(6)

      DO_RESTFLUX = ( LREST_FITMODEL .or. NFILTDEF_FITRESTMAG > 0 )

c generate text strings
      CALL SNLCPAK_DISPLAYTEXT_FIT()

c -------------------------------------------
c load data flux, reject flags, chi2 ...

      DO IFILT = 1, MXFILT_OBS
          VBAND_NDOF(IFILT)   = 0.0
          VBAND_CHI2(IFILT)   = 0.0
          VBAND_PKMJD(IFILT)  = 0.0
          VBAND_PKFLUX(IFILT) = 0.0
      ENDDO

      DO 100 IFILT = 1, NFILT
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)

         IFILTARG  = IFILT
         NFILTARG  = NFILT
         IFILTARG_MAP_SURVEY(IFILTARG) = IFILT_OBS

         IF ( NFILT_REMAP_TABLE > 0 ) THEN
           CALL FILTER_REMAP_FETCH(IFILT_OBS,   ! (I)
     &               IFILTOBS_REMAP, IFILTARG)    ! (O)
           IFILTARG = IFILTARG + 1   ! C -> fortran
           NFILTARG = NFILT_REMAP_TABLE
           IFILTARG_MAP_SURVEY(IFILTARG) = IFILTOBS_REMAP
         ENDIF

         NDOF = int( XNFITDOF(IFILT) )
         IF ( NDOF == 0 ) GOTO 100  ! needed for REMAP filters

c  load each filter with the same PEAK-MJD value
         PKMJD                     = LCVAL_STORE(IPAR_PEAKMJD)
         VBAND_PKMJD(IFILTARG)     = PKMJD
         VBAND_PKMJD_ERR(IFILTARG) = LCERR_STORE(IPAR_PEAKMJD)
         VBAND_NDOF(IFILTARG)      = XNFITDOF(IFILT)     ! Ndof
         VBAND_CHI2(IFILTARG)      = LC_FITCHI2(IFILT)   ! chi2 per filter

c peak flux
         cor   =  PEAKFLUX_OBS_MODEL_COR(ifilt)
         Fpeak =  PEAKFLUX_OBS_MODEL(ifilt) * cor
         Fperr =  PEAKFLUX_OBS_MODEL_ERR(ifilt) * cor
         VBAND_PKFLUX(IFILTARG)     = Fpeak
         VBAND_PKFLUX_ERR(IFILTARG) = Fperr
 100  CONTINUE


c - - - - - - - - - - -

      NOBS = 0
      DO 101 i   = 1, NFITDATA + NFITDATA_REJECT

         NOBS = NOBS + 1

         IF ( NOBS .GT. MXEP_SNLCPAK ) THEN
            write(C1ERR,661) NOBS, MXEP_SNLCPAK
 661        format('NOBS=',I5,' exceeds bound of MXEP_SNLCMAX=',I5)
            c2err = 'Increase bound for data array.'
            CALL MADABORT('SNLCPLOT(SNFIT)', C1ERR, C2ERR)
         ENDIF

         IFILT_OBS       = I4EP_FIT(i,IEP_IFILT_OBS)
         VFILTOBS(NOBS)  = IFILT_OBS

c Dec 10 2017: check for filter-remap option
         IF ( NFILT_REMAP_TABLE > 0 ) THEN
           CALL FILTER_REMAP_FETCH(IFILT_OBS,            ! (I)
     &               IFILTOBS_REMAP, IFILT_REMAP_TMP)    ! (O)
            VFILTOBS(NOBS)  = IFILTOBS_REMAP
         ENDIF

         VMJD(NOBS)         = R4EP_FIT(i,JEP_MJD) + MJDOFF
         VTOBS(NOBS)        = R4EP_FIT(i,JEP_TOBS)
         VFLUXOBS(NOBS)     = R4EP_FIT(i,JEP_DATAFLUX)
         VFLUXOBS_ERR(NOBS) = R4EP_FIT(i,JEP_DATAFLUX_ERR)
         VREJECT(NOBS)      = I4EP_FIT(i,IEP_REJECT)
         VCHI2(NOBS)        = R4EP_FIT(i,JEP_DELCHI2)
         VSIMFLUXOBS(NOBS)  = R4EP_FIT(i,JEP_SIM_FLUXCAL)  ! May 20 2016
         VZERO(NOBS)        = 0.0

         IF ( DO_RESTFLUX ) THEN
           VFILTREST(NOBS)    = I4EP_FIT(i,IEP_IFILT_REST1)
           VFLUXREST(NOBS)    = R4EP_FIT(i,JEP_DATAFLUX_REST)
           VKCOR(NOBS)        = R4EP_FIT(i,JEP_KCOR)
           VAVWARP(NOBS)      = R4EP_FIT(i,JEP_AVWARP)
           VSIMFLUXREST(NOBS) = R4EP_FIT(i,JEP_SIM_FLUXREST)
         ENDIF
 101  CONTINUE

      CALL SNLCPAK_DATA(CCID, NOBS, VMJD,VTOBS, VFLUXOBS, VFLUXOBS_ERR,
     &     VFILTOBS, SNLCPAK_EPFLAG_FLUXDATA, LENCCID)

c store REJECT flags
      CALL SNLCPAK_DATA(CCID, NOBS, VMJD,VTOBS, VREJECT, VDUMERR,
     &     VFILTOBS, SNLCPAK_EPFLAG_REJECT, LENCCID)

c store data-FITFUN chi2
      CALL SNLCPAK_DATA(CCID, NOBS, VMJD,VTOBS, VCHI2, VDUMERR,
     &     VFILTOBS, SNLCPAK_EPFLAG_CHI2, LENCCID)

      IF ( LSIM_SNANA .or. LSIM_MAGOBS ) THEN
c      pack generated SIM fluxes (May 20 2016)
        CALL SNLCPAK_DATA(CCID, NOBS, VMJD, VTOBS,
     &     VSIMFLUXOBS, VZERO,   ! VZERO = zero error for each true flux
     &     VFILTOBS, SNLCPAK_EPFLAG_FLUXSIM, LENCCID)
      ENDIF

c Jan 2014: store rest-frame filter and flux (mlcs,snoopy ...)
c Jan 2020: add KCOR and AVwarp

      IF ( DO_RESTFLUX ) THEN
        CALL SNLCPAK_DATA(CCID, NOBS, VMJD, VTOBS, VFLUXREST, VDUMERR,
     &     VFILTREST, SNLCPAK_EPFLAG_FLUXREST, LENCCID)

        CALL SNLCPAK_DATA(CCID, NOBS, VMJD, VTOBS, VKCOR, VDUMERR,
     &     VFILTREST, SNLCPAK_EPFLAG_KCOR, LENCCID)

        CALL SNLCPAK_DATA(CCID, NOBS, VMJD, VTOBS, VAVWARP, VDUMERR,
     &     VFILTREST, SNLCPAK_EPFLAG_AVWARP, LENCCID)

        if ( LSIM_SNANA ) then
           CALL SNLCPAK_DATA(CCID, NOBS, VMJD, VTOBS,
     &       VSIMFLUXREST, VDUMERR, VFILTREST,
     &       SNLCPAK_EPFLAG_SIMFLUXREST, LENCCID)
        endif
      ENDIF

c store filter-dependent quantities.

      VMJD(1)  = -9999.
      VTOBS(1) = -9999.0  ! dummy for unused TOBS arg
      CALL SNLCPAK_DATA(CCID, NFILTARG, VMJD, VTOBS,
     &     VBAND_NDOF, VDUMERR,
     &     IFILTARG_MAP_SURVEY, SNLCPAK_BANDFLAG_NDOF, LENCCID)

      CALL SNLCPAK_DATA(CCID, NFILTARG, VMJD, VTOBS,
     &     VBAND_CHI2, VDUMERR,
     &     IFILTARG_MAP_SURVEY, SNLCPAK_BANDFLAG_CHI2, LENCCID)

      CALL SNLCPAK_DATA(CCID, NFILTARG, VMJD, VTOBS,
     &   VBAND_PKFLUX,VBAND_PKFLUX_ERR,
     &   IFILTARG_MAP_SURVEY, SNLCPAK_BANDFLAG_PKFLUX, LENCCID)

      CALL SNLCPAK_DATA(CCID, NFILTARG, VMJD, VTOBS,
     &   VBAND_PKMJD,VBAND_PKMJD_ERR,
     &   IFILTARG_MAP_SURVEY, SNLCPAK_BANDFLAG_PKMJD, LENCCID)

c ---------------------------------------
c load best-fit model

      NOBS = 0
      TMIN = -60.0
      TMAX = 140.0
      TBIN = DTOBS_MODEL_PLOT
      NBT  = int( (TMAX-TMIN+1.0E-6)/TBIN )

      DO 510 IFILT = 1, NFILT

         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         if ( .not. USE_FILT(ifilt_obs) ) goto 510

      DO 520 i  = 1, NBT
        NOBS    = NOBS + 1

         IF ( NOBS .GT. MXEP_SNLCPAK ) THEN
            write(C1ERR,661) NOBS, MXEP_SNLCPAK
            c2err = 'Increase bound for best-fit array.'
            CALL MADABORT('SNLCPLOT(SNFIT)', C1ERR, C2ERR)
         ENDIF

        xi      = float(i) - 0.5
        TOBS    = TMIN + TBIN * xi
        VFILTOBS(NOBS)      = IFILT_OBS
        VMJD(NOBS)          = TOBS + PKMJD + MJDOFF
        VTOBS(NOBS)         = TOBS
        VFLUXOBS(NOBS)      = GET_FLUX_FITFUN(ifilt_obs, Tobs,  0)
        VFLUXOBS_ERR(NOBS)  = GET_FLUX_FITFUN(ifilt_obs, Tobs, 60)

c Dec 10 2017: check for filter-remap option
        IF ( NFILT_REMAP_TABLE > 0 ) THEN
          CALL FILTER_REMAP_FETCH(IFILT_OBS,            ! (I)
     &              IFILTOBS_REMAP, IFILT_REMAP_TMP)    ! (O)
          VFILTOBS(NOBS)  = IFILTOBS_REMAP
        ENDIF

         IF ( DO_RESTFLUX ) THEN
           VFILTREST(NOBS) = -9
           VFLUXREST(NOBS) = -999.
         ENDIF

 520  CONTINUE
 510  CONTINUE

      call flush(6)

      CALL SNLCPAK_DATA(CCID, NOBS, VMJD,VTOBS, VFLUXOBS, VFLUXOBS_ERR,
     &     VFILTOBS, SNLCPAK_EPFLAG_FITFUN, LENCCID)

c fill output structure and write to disk
      CALL SNLCPAK_FILL(CCID, LENCCID)

c set global flag.
      MADE_LCPLOT = .TRUE.

      RETURN
      END   ! end of SNLCPLOT

C ============================================
CDECK  ID>,  SNPKTEXT. 
      SUBROUTINE SNLCPAK_DISPLAYTEXT_FIT()

      IMPLICIT NONE
c Create strings and pass them to generic wrapper SNLCPAK_DISPLAYTEXT()
c
c May 2013: tack on optional FITMAGDIF result


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.    public snana.car inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.    fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


      CHARACTER
     &   CCID*(MXCHAR_CCID), TEXT_forC*80
     &  ,CPAR*20, SPAR*20
     &  ,cDIST*60, cZPH*60, cCHI2*60
     &  ,cMAGDIF*28

      INTEGER
     &   LENCCID, LENTEXT, LENc, LENs, LENDIST, LENZPH, LENCHI2
     &  ,NDOF

      REAL*8  D, DERR, ZPH, ZPHERR, CHI2

      REAL*4 MAGVAL4, MAGERR4, PROB_MAGDIF4(2)

      LOGICAL LTMP

C -------------- BEGIN ------------

      LENCCID = ISNLC_LENCCID
      CCID = SNLC_CCID(1:LENCCID) // char(0)

      LENTEXT = LEN(TEXT_forC)

c ----------------------------------
c type and redshift
      write(TEXT_forC,40) ISNLC_TYPE,
     &                SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
 40   format('TYPE = ', I3, 5x,'z = ', F5.3,' +- ', F5.3 )


c tack on optional FITMAGDIF result (May 2013)
      LTMP = FILTER_FITMAGDIF .NE. ''
      CALL GET_FITMAGDIF(MAGVAL4, MAGERR4, PROB_MAGDIF4 )
      IF ( LTMP .and. MAGERR4 .GE. 0.0 ) THEN
         write(cMAGDIF,44) FILTER_FITMAGDIF, MAGVAL4, MAGERR4
44       format('DELTA',A1,' = ', F5.2, ' +-',F5.2)
         TEXT_forC = TEXT_forC(1:50) // cMAGDIF
      ENDIF

c termination char
      TEXT_forC = TEXT_forC(1:LENTEXT-1) // char(0)

      CALL SNLCPAK_DISPLAYTEXT(CCID, TEXT_forC, LENCCID, LENTEXT )

c ----------------------------------
c color and stretch params
      CPAR = PARNAME_STORE(IPAR_COLOR) ;  LENc = INDEX(CPAR, ' ') - 1
      SPAR = PARNAME_STORE(IPAR_SHAPE) ;  LENs = INDEX(SPAR, ' ') - 1
      write(TEXT_forC,41)
     &    CPAR(1:LENc)
     &   ,LCVAL_STORE(IPAR_COLOR), LCERR_STORE(IPAR_COLOR)
     &   ,SPAR(1:LENs)
     &   ,LCVAL_STORE(IPAR_SHAPE), LCERR_STORE(IPAR_SHAPE)
     &   ,char(0)
 41   format(A,' = ',F6.3, ' +-', F6.3, 5x,
     &       A,' = ',F6.3, ' +-', F6.3, A)
      CALL SNLCPAK_DISPLAYTEXT(CCID, TEXT_forC, LENCCID, LENTEXT )

c ---------------------------------
c now distance (MU and or PHOTOZ) and chi2

      cDIST = ''  ; LENDIST = 0
      cZPH  = ''  ; LENZPH  = 0
      cCHI2 = ''  ; LENCHI2 = 0

      if ( INISTP(IPAR_DLMAG) > 0.0 ) then
         D    = LCVAL_STORE(IPAR_DLMAG)  ! MU or x0
         DERR = LCERR_STORE(IPAR_DLMAG)  ! error on above
         if ( D < 0.01 ) then  ! x0 in units of E-4
            write(cDIST,51) 10000.*D, 10000.*DERR
            LENDIST = INDEX(cDIST,'E') + 2
         else if ( D < 2.0 ) then ! x0 in units of E-2
            write(cDIST,52) 100.*D, 100.*DERR
            LENDIST = INDEX(cDIST,'E') + 2
         else  ! it's MU
            write(cDIST,55) D, DERR
            LENDIST = INDEX(cDIST,'+') + 7
         endif
 51      format( 'x0 = ('F6.3, ' +-', F6.3, ')xE-4'  )
 52      format( 'x0 = ('F6.3, ' +-', F6.3, ')xE-2'  )
 55      format( 'mu = ',F6.3, ' +-', F6.3  )
      endif

      if ( INISTP(IPAR_zPHOT) > 0.0 ) then
         ZPH    = LCVAL_STORE(IPAR_zPHOT)
         ZPHERR = LCERR_STORE(IPAR_zPHOT)
         write(cZPH,60) ZPH, ZPHERR
 60      format('zPHOT = ', F6.3, ' +-',F6.3 )
         LENZPH = INDEX(cDIST,'+') + 7
      endif

c and finall the chi2/dof
      CHI2 = LCCHI2_STORE(1)
      NDOF = INT( XNFITDOF(0))
      if ( CHI2 .LT. 999.99 ) then
        write(cCHI2,71) CHI2, NDOF
        LENCHI2 = 24
      else
        write(cCHI2,72) CHI2, NDOF
        LENCHI2 = 27
      endif
 71   format('chi2/dof = ',F5.1,' /', I5)
 72   format('chi2/dof = ',F8.1,' /', I5)



c glue the pieces together into one string.

      TEXT_forC = cDIST(1:LENDIST) // '   '
     &         // cZPH(1:LENZPH)   // '   '
     &         // cCHI2(1:LENCHI2) // char(0)

      CALL SNLCPAK_DISPLAYTEXT(CCID, TEXT_forC, LENCCID, LENTEXT )

      RETURN
      END



C =====================================================
CDECK  ID>,  TABLE_SNFIT. 
      SUBROUTINE TABLE_SNFIT(ID,IFLAG)

C Created Feb 1, 2013
C Book and load table.
c
c ID    = table identifier
c IFLAG = IFLAG_INI or IFLAG_ANA
c
c
c     HISTORY
c July 19 2016: call TABLE_STRING_TERMINATION(+1/-1)
c               to protect strings for ROOT.
c
c Apr 18 2022: pass ID and IFLAG args
c -----------------------------------------

      IMPLICIT NONE

      INTEGER ID, IFLAG

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      INTEGER i, LENNAME, LENFMT
      CHARACTER NAME*40, TEXTFMT*20, TEXTFMT_forC*20
      LOGICAL CREATE_FILE

c ----------------- BEGIN ------------------------

cc xxxx      ID = IDTABLE_FITRES

c ----------------------------------

      IF ( IFLAG == IFLAG_INI ) THEN

         NAME    = 'FITRES' // char(0)
         LENNAME  = INDEX(NAME,   ' ') - 1

         TEXTFMT  = TEXTFORMAT_TABLE(ITABLE_FITRES)
         LENFMT   = INDEX(TEXTFMT,' ') - 1
         TEXTFMT_forC = TEXTFMT(1:LENFMT) // char(0)

         CALL SNTABLE_CREATE(ID,NAME,TEXTFMT_forC, LENNAME,LENFMT)  ! C fun

           CALL INIT_TABLE_SNANAVAR(ID, 'SNANA', 2)
           CALL INIT_TABLE_SNFITVAR(ID, 'SNFIT'   )

c         optional epoch-dependent par
          IF ( OPT_TABLE(ITABLE_FITRES) .EQ. 2 ) THEN
             CALL INIT_TABLE_SNFITEP(ID, 'SNFITEP')
          ENDIF

c       for sims ...
          IF ( LSIM_SNANA ) THEN
            CALL INIT_TABLE_SIMVAR(ID, 'SIMVAR')
          ENDIF

        RETURN
      ENDIF

c ------------------------------------
c  fill table

      IF ( IFLAG == IFLAG_ANA ) THEN

c   terminate strings for C table-functions (snana.car routine)
        CALL TABLE_STRING_TERMINATION(+1)

        CALL SNTABLE_FILL(ID)  ! generic C function

        CALL TABLE_STRING_TERMINATION(-1)  ! remove termination
      END IF

c ------------------------------------

      RETURN
      END  ! end of TABLE_SNFIT


C =====================================
CDECK  ID>,  TBFITVAR. 
      SUBROUTINE INIT_TABLE_SNFITVAR(ID,BLOCK)
c
c Created Feb 1, 2013
c
c Initialize variables for snfitres-analysis table.
c Call generic function SNTABLE_ADDCOL() that loads a table
c for each selected format: CERNLIB, ROOT, HDF5 ...
c The VARLIST string is constructed for HBNAME so that it trivially
c works for HBOOK; will need extra parsing (in SNTABLE_ADDCOL)
c for root and hdf5.
c
c This routine is intended to replace CWNT_HBNAMES_SNFITVAR()
c
c Apr 29, 2013:
c    ERR_[PARNAME] -> [PARNAME]ERR to have same names in the
c    text/fitres file. Also changed PHOTOZ -> ZPHOT in FITPAR_INI
c    Note extra SUFFIX arg in TABLE_PARNAMES.
c
c    ERRFLAG[ipar1][ipar2] -> ERRFLAG_[parname]
c
c    RHO[ipar1][ipar2] -> REDCOV_[nam1]_[nam2]
c         and add COV_[nam1]_[nam2]
c
c June 14, 2013: add optional Zmax variables for 1/Vmax option
c
c Jan  4 2016: add MNSTAT_COV
c Aug 29 2017: add fit params for IDEAL fit
c
c Mar 19 2018:
c   + call function SKIPTABLE_FITPAR(VARNAME)
c   + write OPT_PHOTOZ to table if ZPHOT info is suppressed.
c
c Nov 11 2019:
c  Protect adding non-PKMJD covariance columns if there aren't any
c  when stretch and color are both fixed instead of floated.
c
c Mar 02 2022: add zPRIOR and zPRIOR_ERR
c
c --------------

      IMPLICIT NONE
      INTEGER   ID          ! (I) table id
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK

c local var

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,USRTAGCM. inserted below by ypatchy. 

      INTEGER MXUSERTAG
      PARAMETER ( MXUSERTAG = 1000 ) ! max number of user tags

      INTEGER
     &   N_USERTAGS           ! number of tags in USERTAGS_FILE
     &  ,USERTAG_VALUELIST(MXUSERTAG)  ! list of user tags
     &  ,USERTAG                   ! USERTAG value  for current SN

      BYTE
     &   USERTAG_USED(MXUSERTAG)   ! mark when each USERTAG is used

      CHARACTER
     &   USERTAG_CCIDLIST(MXUSERTAG)*(MXCHAR_CCID)  ! list of CCID

      COMMON / USERTAGCOM /
     &   N_USERTAGS, USERTAG_VALUELIST, USERTAG_CCIDLIST
     &  ,USERTAG, USERTAG_USED



C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


C +CDE,VMAXCOM. inserted below by ypatchy. 

c Created Jun 2013 by R.K.

c Examples for OPT_VMAX
c  OPT_VMAX = 2 -> use obs for mag, peak for Zmax
c  OPT_VMAX = 3 -> use peak for both mag and Zmax


      INTEGER
     &  MXFILT_VMAX
     & ,OPTBIT_MAG    ! Zmax at epoch of max obs brightness
     & ,OPTBIT_ZMAX
     & ,OPTBIT_VERBOSE

      REAL*8  MAGDIF_CONVERGE

      PARAMETER (
     &   MXFILT_VMAX   = 5
     &  ,OPTBIT_MAG    = 0  ! bit0 off/on -> mag at best-fit obs/peak
     &  ,OPTBIT_ZMAX   = 1  ! bit1 off/on -> zmax from best-fot obs/peak
     &  ,OPTBIT_VERBOSE = 7 ! bit7(128) -> verbose printout
     &  ,MAGDIF_CONVERGE = 0.001 ! stop when |mag(zmax)-MAGLIM| < CONVERGE
     &     )

      INTEGER
     &   NFILT_VMAX   !Number of obs filters to compute Zmax/Vmax
     &  ,IFILTOBS_LIST_VMAX(MXFILT_VMAX) ! sparse list

      REAL
     &   MAGLIM_LIST_VMAX(MXFILT_VMAX)
     &  ,TREST_LIST_VMAX(MXFILT_VMAX)
     &  ,MAG_LIST_VMAX(MXFILT_VMAX)
     &  ,Z_LIST_VMAX(MXFILT_VMAX)
     &  ,VOL_LIST_VMAX(MXFILT_VMAX)

      INTEGER NEP_LIST_VMAX(MXFILT_VMAX)

      CHARACTER FILTLIST_VMAX*20

      COMMON/ VMAXCOM /
     &    NFILT_VMAX, IFILTOBS_LIST_VMAX
     &   ,FILTLIST_VMAX, MAGLIM_LIST_VMAX
     &   ,TREST_LIST_VMAX, MAG_LIST_VMAX, Z_LIST_VMAX, VOL_LIST_VMAX
     &   ,NEP_LIST_VMAX

C ===================================

C +CDE,FITIDEALCOM. inserted below by ypatchy. 

      INTEGER SIMFIT_IDEAL_DEBUG
      PARAMETER (SIMFIT_IDEAL_DEBUG=777)   ! do nominal fit twice

      LOGICAL DOFIT_IDEAL_EVENT ! refers to both ideal and nominal fit for this event
      LOGICAL DOFIT_IDEAL       ! =T for ideal fit, =F for nominal fit that follows
      INTEGER NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
      REAL*4
     &    SAVE_FLUXCAL(MXEPOCH), SAVE_MWEBV, SAVE_MWEBV_ERR
     &   ,FITPAR_IDEAL(20)
      COMMON / FITIDEALCOM /
     &   DOFIT_IDEAL_EVENT, DOFIT_IDEAL
     &  ,NFIT_ITERATION_ORIG, NFIT_ITERATION_IDEAL
     &  ,SAVE_FLUXCAL, SAVE_MWEBV, SAVE_MWEBV_ERR, FITPAR_IDEAL


      INTEGER IPAR_START
      PARAMETER (IPAR_START=3)  ! skip ISN and ITER for CWN

      INTEGER
     &    IFILT, IFILT_OBS, OPT_STORE, USE4TEXT
     &   ,LENLIST, LENPKMJD, LENNAME, LENNAME2, LENBLOCK, LENPACK
     &   ,NTPAR_MIN, NTPAR_MAX, NTPAR, ipar

      LOGICAL   LTMP
      CHARACTER varlist*1000, VARNAME*60, STR_IPACK*40, CBLOCK*40
      CHARACTER CFILT*1, SUFFIX_R*12, SUFFIX_I*12, PNAM*40

      LOGICAL  SKIPTABLE_FITPAR  ! function

      EXTERNAL
     &    SNTABLE_ADDCOL
     &   ,SNTABLE_ADDCOL_int
     &   ,SNTABLE_ADDCOL_flt
     &   ,SNTABLE_ADDCOL_dbl
     &   ,SNTABLE_ADDCOL_str

C ---------------- BEGIN ------------

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5)
      call flush(6)

      LENBLOCK = INDEX(BLOCK//' ',' ') - 1
      LENLIST  = LEN(VARLIST)
      CBLOCK   = BLOCK(1:LENBLOCK) // char(0)

c mar 18 2018: write OPT_PHOTOZ if ZPHOT output is suppressed
      IF ( .not. WRTABLEFILE_ZPHOT ) then
         VARLIST = 'OPT_PHOTOZ:I' // char(0)
         LENLIST = INDEX(VARLIST, ' ') - 1
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, OPT_PHOTOZ,
     &           VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST )
      ENDIF

c - - - - start with SNANA-analogs that could not be computed in snana

      CALL TABLE_VARLIST_FILTERS('SNRMAX','F',SURVEY_FILTERS_TABLE,
     &        VARLIST, LENLIST)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBL_SNRMAX(1),
     &           VARLIST(1:LENLIST)//char(0),0, LENBLOCK, LENLIST )


      CALL TABLE_VARLIST_FILTERS('XTMW', 'F', SURVEY_FILTERS_TABLE,
     &        VARLIST, LENLIST)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBL_XTMW(1),
     &           VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST )
      LENLIST = LEN(VARLIST)

c - - - - fit parameters and errors (skip BIDON values)

      NTPAR_MIN = IPAR_START
      NTPAR_MAX = IPAR_MAX

      DO 380 ipar = NTPAR_MIN, NTPAR_MAX
         VARNAME = PARNAME_STORE(ipar)
         LENNAME = INDEX(VARNAME,' ') - 1

         IF( SKIPTABLE_FITPAR(VARNAME) ) GOTO 380

         VARLIST = VARNAME(1:LENNAME)// ':F'   ! include cast
         LENLIST = INDEX(VARLIST,' ') - 1
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, LCVAL_STORE(ipar),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)

c now the fitted error.
         VARLIST  = VARNAME(1:LENNAME) // 'ERR:F'
         LENLIST  = INDEX(VARLIST,' ') - 1
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, LCERR_STORE(ipar),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)

 380  CONTINUE


c ----------------------------------------------------
c check for additional IDEAL fit with FLUX = TRUEFLUX

      IF ( SIMFIT_IDEAL_PRESCALE > 0  ) THEN
        DO 381 ipar = NTPAR_MIN, NTPAR_MAX
          VARNAME = PARNAME_STORE(ipar)
          LENNAME = INDEX(VARNAME,' ') - 1

          IF ( SKIPTABLE_FITPAR(VARNAME) ) GOTO 381

          VARLIST = VARNAME(1:LENNAME)// '_IDEAL:F'   ! include cast
          LENLIST = INDEX(VARLIST,' ') - 1
          CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, FITPAR_IDEAL(ipar),
     &        VARLIST(1:LENLIST)//char(0), 1, LENBLOCK, LENLIST)
 381  CONTINUE

      ENDIF

c ----------------------------------------------------
c marginalized PDF-probs
      IF ( NGRID_PDF > 0 ) THEN

         DO 388 ipar = 3, IPAR_MAX  ! skip ISN and ITER
            PNAM    = PARNAME_STORE(IPAR)
            if ( PNAM(1:5) .EQ. 'BIDON' ) GOTO 388
            LENNAME = INDEX(PNAM,' ') - 1
            VARNAME = 'PDFPROB_' // PNAM(1:LENNAME) // ':F' // char(0)
            CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PDFPROB2_STORE(IPAR),
     &           VARNAME, 0, LENBLOCK, 30)
 388    CONTINUE

      ENDIF

c - - - - -  ERRFLAGs - - - - - -

      CALL TABLE_VARLIST_ERRFLAG(NTPAR_MIN, NTPAR_MAX, VARLIST, LENLIST)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, ERRTYPE_STORE(NTPAR_MIN),
     &        VARLIST(1:LENLIST)//char(0), 0, LENBLOCK, LENLIST)

c - - - - - -
c add Covariance status (Jan 2016) from MNSTAT call
c  MNSTAT_COV  = 2 -> was forced to be pos-definite
c              = 3 -> full accurate coc matrix
c  MNSTAT_COV  < 2 -> bad matrix and is rejected

      VARLIST = 'MNSTAT_COV:I' // char(0)
      LENLIST = LEN(VARLIST)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, MNSTAT_COV, VARLIST, 0,
     &                   LENBLOCK, LENLIST)

c - - - - correlations - - - - - -

c reduced covariance (-1 <= RHO <=  +1)
      USE4TEXT = 0
      CALL TABLE_VARLIST_COV(1, VARLIST, LENLIST, LENPKMJD )
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBL_REDCOV(1),
     &        VARLIST(1:LENLIST)//char(0), USE4TEXT, LENBLOCK,LENLIST)


c full covariance;
      CALL TABLE_VARLIST_COV(2, VARLIST, LENLIST, LENPKMJD )

c add PKMJD-covariances
      IF (LENPKMJD > 0 ) THEN
         USE4TEXT = 0
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBL_COV(1),
     &        VARLIST(1:LENPKMJD)//char(0), USE4TEXT, LENBLOCK,LENPKMJD)
      ENDIF

c add other [non-PKMJD] covariances and include in optional text table.
c Make sure to skip the comma after the PKMJD-covariance list.
      IF ( LENLIST > LENPKMJD ) THEN
        USE4TEXT = 1
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBL_COV(NCOV_TBL_PKMJD+1),
     &        VARLIST(LENPKMJD+2:LENLIST)//char(0),
     &        USE4TEXT, LENBLOCK, LENLIST-LENPKMJD )
      ENDIF
c - - - - - -   PHOTOZ - - - - -

      LENLIST = LEN(VARLIST)

      IF ( DOFIT_PHOTOZ ) THEN

        VARLIST = 'zPRIOR:F,zPRIORERR:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PRIOR_PHOTOZ,
     &                VARLIST,1,       LENBLOCK, LENLIST)

        VARLIST = 'ZPULL:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PHOTOZ_ERR_ZPULL,
     &              VARLIST,0,     LENBLOCK, LENLIST)

        VARLIST = 'NEARDROP:I' // char(0)
        CALL SNTABLE_ADDCOL_int(ID, CBLOCK, IFILT_NEARDROP,
     &              VARLIST,0,     LENBLOCK, LENLIST)

        VARLIST = 'DZMIN1:F,DZMIN2:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PHOTODZ_MIN(1),
     &              VARLIST,0,     LENBLOCK, LENLIST)

        VARLIST = 'DZ1ZMIN1:F,DZ1ZMIN2:F' // char(0)
        CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, PHOTODZ1Z_MIN(1),
     &              VARLIST,0,      LENBLOCK, LENLIST)

      ENDIF

c - - - - -  misc. variables - - - -

      DO 333 IPAR = IPAR_MAX+1, NPLOTPAR
         VARNAME  = PARNAME_STORE(ipar)
         LENNAME  = INDEX(VARNAME,' ') - 1
         VARLIST  = VARNAME(1:LENNAME)// ':F'   ! include cast
         LENLIST  = INDEX(VARLIST,' ') - 1
         USE4TEXT = PAROPT_STORE(ipar)

         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, LCVAL_STORE(ipar),
     &        VARLIST(1:LENLIST)//char(0), USE4TEXT,
     &         LENBLOCK, LENLIST )

 333  CONTINUE

c - - - - - - - - - - - - - - - - - - - -

      LENLIST = LEN(VARLIST)

c - - - - - NFILT used in fit - - - - -

      VARLIST = 'NFILT_USEFIT:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NFILT_OBS_USEFIT,
     &              VARLIST, 0,     LENBLOCK, LENLIST)

c - - - - - Zmax for 1/Vmax option

      DO 404 IFILT = 1, NFILT_VMAX

         CFILT = FILTLIST_VMAX(IFILT:IFILT)
         SUFFIX_R = '_' // CFILT // ':F' // char(0)
         SUFFIX_I = '_' // CFILT // ':I' // char(0)

         VARLIST = 'mag_Vmax' // SUFFIX_R
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, MAG_LIST_VMAX(ifilt),
     &        VARLIST, 0, LENBLOCK, LENLIST)

         VARLIST = 'Trest_Vmax' // SUFFIX_R
         CALL SNTABLE_ADDCOL_flt(ID,CBLOCK,TREST_LIST_VMAX(ifilt),
     &           VARLIST, 0, LENBLOCK, LENLIST)

         VARLIST = 'z_Vmax' // SUFFIX_R
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, z_LIST_VMAX(ifilt),
     &            VARLIST, 0, LENBLOCK, LENLIST)

         VARLIST = 'vol_Vmax' // SUFFIX_R
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, VOL_LIST_VMAX(ifilt),
     &          VARLIST, 0, LENBLOCK, LENLIST)

         VARLIST = 'NEP_Vmax' // SUFFIX_I
         CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NEP_LIST_VMAX(ifilt),
     &        VARLIST, 0, LENBLOCK, LENLIST)

 404  CONTINUE

      RETURN
      END   ! end of  INIT_TABLE_SNFITVAR


C =====================================
CDECK  ID>,  SKIPTABLE_FITPAR. 
      LOGICAL FUNCTION SKIPTABLE_FITPAR(VARNAME)

c Created Mar 2018
c Return TRUE if this variable should be suppressed
c from table output.
c
c Jan 2024: check x2

      IMPLICIT NONE
      CHARACTER VARNAME*(*)  ! (I) name of fitpar variable to check


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





      LOGICAL  SKIP

c ------------- BEGIN -------------
      SKIP = .FALSE.

      IF ( VARNAME(1:5) .EQ. 'BIDON'    ) SKIP = .TRUE.
      IF ( VARNAME(1:8) .EQ. 'REDSHIFT' ) SKIP = .TRUE.

      IF ( VARNAME(1:2) .EQ. 'x2' .and. NSHAPEPAR==1) SKIP = .TRUE.

      IF ( VARNAME(1:5) .EQ. 'zPHOT' ) THEN
        IF ( DOFIT_PHOTOZ .and. (.not.WRTABLEFILE_ZPHOT) )then
           SKIP = .TRUE.
        ENDIF
      ENDIF

      SKIPTABLE_FITPAR = SKIP
      RETURN
      END

C ========================================
CDECK  ID>,  TBFITEP. 
      SUBROUTINE INIT_TABLE_SNFITEP(ID,BLOCK)

c Created Feb 2, 2013

c Init table for epoch-dependent variables.
c (replaces CWNT_HBNAMES_RESID)
c
c Feb 22 2016: always do the extra EP variables, even for TERSE format.
c              See EXTRA_EPVAR
c
c Jul 22 2017: add BAND (character for IFILT_OBS)
c Jan 23 2020: add AVWARP for rest-frame models with k-corrections
c
c ----------------------------------------------

      IMPLICIT NONE
      INTEGER   ID          ! (I) table id
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK (optional)

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      INTEGER LENB, LENV
      CHARACTER CBLK*40, CNFIT*14, VARNAME*40
      LOGICAL EXTRA_EPVAR

      EXTERNAL
     &    SNTABLE_ADDCOL_int
     &   ,SNTABLE_ADDCOL_flt
     &   ,SNTABLE_ADDCOL_dbl
     &   ,SNTABLE_ADDCOL_str

c ---------------- BEGIN ----------------

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5)
      call flush(6)

      LENV   = LEN(VARNAME)
      LENB   = INDEX(BLOCK//' ',' ') - 1
      CBLK   = BLOCK(1:LENB) // char(0)
c --------------------------------

      write(CNFIT,15) MXFIT_DATA
15    format('NPTFIT[',I4.4,']' )  ! no spaces or commas in string
      VARNAME = CNFIT(1:12)  // char(0)  ! Nobs used in fit + NREJECT
      CALL SNTABLE_ADDCOL_int(ID, CBLK, NFITDATA_TOTAL,
     &     VARNAME, 0, LENB,LENV)

      VARNAME = 'REJECT(NPTFIT):I' // char(0)  ! 1 -> rejected from fit
      CALL SNTABLE_ADDCOL_int(ID,CBLK, I4EP_FIT(1,IEP_REJECT),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'MJD(NPTFIT):F'  // char(0)   ! MJD
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_MJD),
     &        VARNAME, 0, LENB, LENV)

      VARNAME = 'TOBS(NPTFIT):F'  // char(0)     ! MJD - PEAKMJD
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_TOBS),
     &        VARNAME, 0, LENB, LENV)

      VARNAME = 'TREST(NPTFIT):F'  // char(0)  ! Tobs/(1+z)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_TREST),
     &         VARNAME, 0, LENB,LENV)

      VARNAME = 'IFILTOBS(NPTFIT):I' // char(0)  ! abs. obs-frame filter indx
      CALL SNTABLE_ADDCOL_int(ID,CBLK, I4EP_FIT(1,IEP_IFILT_OBS),
     &      VARNAME, 0, LENB,LENV)

c xxxxxxxxxxxxxxxxxxxxxx
c Jul 22 2017: add BAND, but beware that MXFIT_DATA must be < 1000
c              to work with HBOOK. Also doens't work right with HBOOK
c              when lower and upper case are mixed: e.g., grGR
c      VARNAME = 'BAND(NPTFIT):C*4' // char(0)  ! abs. obs-frame filter char
c      CALL SNTABLE_ADDCOL(ID,CBLK, BANDEP_FIT(1),
c     &      VARNAME, 0, LENB, LENV)
c xxxxxxxxxxxxxxxxxxxxxx

      VARNAME = 'FLUXCAL_DATA(NPTFIT):F' // char(0)  ! FLUXCAL, data
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_DATAFLUX),
     &        VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXCAL_DATA_ERR(NPTFIT):F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_DATAFLUX_ERR),
     &        VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXCAL_MODEL(NPTFIT):F' // char(0)  ! fluxcal from best-fit
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_MODELFLUX),
     &        VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXCAL_MODEL_ERR(NPTFIT):F' // char(0)  ! error on above
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_MODELFLUX_ERR),
     &        VARNAME, 0, LENB,LENV)

      VARNAME = 'MODELMAG_ERR(NPTFIT):F' // char(0)  ! model error, mag
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_MODELMAG_ERR),
     &       VARNAME, 0, LENB,LENV)

      VARNAME = 'FUDGEFLUX_ERR(NPTFIT):F' // char(0) ! fudge error on flux
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_FUDGEFLUX_ERR),
     &        VARNAME, 0, LENB,LENV)

      VARNAME = 'LAMREST(NPTFIT):F' // char(0)  ! <lam_obs>/(1+z)
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_LAMREST),
     &       VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXDIF(NPTFIT):F' // char(0)  ! data-model flux dif
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_RESID),
     &      VARNAME, 0, LENB,LENV)

      VARNAME = 'FLUXDIF_ERR(NPTFIT):F' // char(0)  ! dif err,include model err
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_RESID_ERR),
     &       VARNAME, 0, LENB,LENV)

      VARNAME = 'MAGDIF(NPTFIT):F' // char(0)  ! data-model magDif
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_MAGDIF),
     &       VARNAME, 0, LENB,LENV)

      VARNAME = 'CHI2FLUX(NPTFIT):F' // char(0)  ! (DIF/DIF_ERR)**2
      CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_DELCHI2),
     &       VARNAME, 0, LENB,LENV)


      IF ( LSIM_SNANA .or. LSIM_MAGOBS ) THEN
         VARNAME = 'FLUXCAL_SIM(NPTFIT):F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SIM_FLUXCAL),
     &        VARNAME, 0, LENB,LENV)

         VARNAME = 'CHI2FLUX_SIM(NPTFIT):F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SIM_DELCHI2),
     &        VARNAME, 0, LENB,LENV)
      ENDIF

c extra 'observing' variables

      EXTRA_EPVAR = .TRUE.
      IF ( EXTRA_EPVAR ) THEN
        VARNAME = 'PSF(NPTFIT):F' // char(0)  ! PSF-sigma arcsec
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_PSF),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'NEA(NPTFIT):F' // char(0)  ! noise-equiv-area, asec^2
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_NEA),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'SKYSIG(NPTFIT):F' // char(0)  ! sky noise per pixel
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SKYSIG),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'SKYSIG_T(NPTFIT):F' // char(0)  ! templ noise per pixel
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SKYSIG_T),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'ZP(NPTFIT):F' // char(0)  ! zeropoint, FLUX(ADU) to mag
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_ZP),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'ZP_ERR(NPTFIT):F' // char(0)  ! error on above
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_ZPERR),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'GAIN(NPTFIT):F' // char(0)  ! e/ADU
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_GAIN),
     &       VARNAME, 0, LENB,LENV)

        if ( SNLC_NXPIX > 0 ) then
           VARNAME = 'XPIX(NPTFIT):F' // char(0)
           CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_XPIX),
     &          VARNAME, 0, LENB,LENV)

           VARNAME = 'YPIX(NPTFIT):F' // char(0)
           CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_YPIX),
     &          VARNAME, 0, LENB,LENV)

           VARNAME = 'AREAFRAC(NPTFIT):F' // char(0)
           CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_AREAFRAC),
     &          VARNAME, 0, LENB,LENV)
        endif

        VARNAME = 'SKYFLUXCAL(NPTFIT):F' // char(0)  ! FLUXCAL(SKY)/pix
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SKYFLUXCAL),
     &       VARNAME, 0, LENB,LENV)

        VARNAME = 'SBFLUXCAL(NPTFIT):F' // char(0)  ! host surf. bright/asec^2
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SBFLUXCAL),
     &         VARNAME, 0, LENB,LENV)

        VARNAME = 'ERRTEST(NPTFIT):F' // char(0)  ! calc/true error ratio
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_ERRTEST),
     &        VARNAME, 0, LENB,LENV)

        VARNAME = 'FLUXERRCALC_SIM(NPTFIT):F' // char(0)  ! calc error
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_ERRCALC),
     &        VARNAME, 0, LENB,LENV)

        VARNAME = 'PHOTPROB(NPTFIT):F' // char(0)  ! Dec 17, 2014
        CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_PHOTPROB),
     &        VARNAME, 0, LENB,LENV)

      ENDIF

c optionl rest-frame info for rest-frame model

      IF ( LREST_FITMODEL .or. NFILTDEF_FITRESTMAG > 0 ) THEN
         VARNAME = 'IFILTREST1(NPTFIT):I' // char(0)  ! nearest IFILT_REST
         CALL SNTABLE_ADDCOL_int(ID,CBLK,I4EP_FIT(1,IEP_IFILT_REST1),
     &         VARNAME, 0, LENB, LENV)

         VARNAME = 'IFILTREST2(NPTFIT):I' // char(0)  ! 2nd nearest IFILT_REST
         CALL SNTABLE_ADDCOL_int(ID,CBLK,I4EP_FIT(1,IEP_IFILT_REST2),
     &         VARNAME, 0, LENB, LENV)

         VARNAME = 'AVWARP(NPTFIT):F' // char(0)  ! AVwarp for kcor
         CALL SNTABLE_ADDCOL_flt(ID,CBLK,R4EP_FIT(1,JEP_AVWARP),
     &         VARNAME, 0, LENB,LENV)

         VARNAME = 'KCOR(NPTFIT):F' // char(0)  ! k correction
         CALL SNTABLE_ADDCOL_flt(ID,CBLK,R4EP_FIT(1,JEP_KCOR),
     &         VARNAME, 0, LENB,LENV)

         VARNAME = 'FLUXCAL_REST(NPTFIT):F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID,CBLK,R4EP_FIT(1,JEP_DATAFLUX_REST),
     &         VARNAME, 0, LENB,LENV)

         IF ( LSIM_SNANA ) THEN
           VARNAME = 'SIM_FLUXCAL_REST(NPTFIT):F' // char(0)
           CALL SNTABLE_ADDCOL_flt(ID,CBLK,R4EP_FIT(1,JEP_SIM_FLUXREST),
     &          VARNAME, 0, LENB,LENV)

           VARNAME = 'SIM_MAGREST(NPTFIT):F' // char(0)
           CALL SNTABLE_ADDCOL_flt(ID,CBLK, R4EP_FIT(1,JEP_SIM_MAGREST),
     &          VARNAME, 0, LENB,LENV)
         ENDIF

      ENDIF

      RETURN
      END   ! end of INIT_TABLE_SNFITEP

C ======================
CDECK  ID>,  TBVARERR. 
      SUBROUTINE TABLE_VARLIST_ERRFLAG(IPAR_MIN,IPAR_MAX,
     &                                 VARLIST,LENLIST )

C Created Sep 2012
c Return VARLIST string for HBNAME call to initialize ERRFLAGs.
c
c Feb  5, 2013: return LENLIST
c Apr 29, 2013: ERRFLAG_[ipar] -> ERRFLAG_[name] to be more clear
c
c ----------------------------

c subroutine args

      IMPLICIT NONE
      INTEGER IPAR_MIN, IPAR_MAX  ! (I) IPAR range
      CHARACTER VARLIST*(*)       ! (O) comma-separate par-name list
      INTEGER   LENLIST           ! (O) length of VARLIST

c local var

C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

      INTEGER ipar,  LENNAME, LENPACK
      character CTMP*20, C2*2, STR_IPACK*40, NAME*40

C ----------- BEGIN ------------

      do ipar = IPAR_MIN, IPAR_MAX

         write(c2,22) ipar
22       format(I2.2)

         NAME    = PARNAME_STORE(IPAR)
         LENNAME = INDEX(NAME,' ') - 1

         CTMP = 'ERRFLAG_' // NAME(1:LENNAME) // ':I'

         if ( ipar  .EQ. IPAR_MIN ) then
            VARLIST = CTMP
         else
            LENLIST = INDEX(VARLIST,' ') - 1
            VARLIST = VARLIST(1:LENLIST) // ',' // CTMP
         endif
      enddo

      LENLIST = INDEX(VARLIST,' ') - 1

      RETURN
      END

C =======================================================
CDECK  ID>,  TBLVARCOV. 
      SUBROUTINE TABLE_VARLIST_COV(FLAGCOV,VARLIST,LENLIST,LENPKMJD)

c Created Sep 2012
c Return covariance VARLIST to pass to SNTABLE_ADDCOL().
c
c Input:
c   FLAGCOV   = 1, 2 --> reduced, full covariance
c
c Outputs:
c   VARLIST  = string to pass to SNTABLE_ADDCOL.
c   LENLIST  = length of entire varlist
c   LENPKMJD = length of sub-list with only the PKMJD elements.
c
c In addition to return arguments, the following globals
c are also computed to help evaluate the COV arrays needed
c to fill the SNTABLE(s).
c
c   NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
c
c          HISTORY
c        ~~~~~~~~~~~
c
c Apr 29 2013: RHO -> REDCOV and replace IPAR with PARNAME_STORE
c              e.g., RHO34 -> REDCOV_pkmjd_x1
c
c May 13 2014:
c   - remove terms with BIDON and add FLAGPKMJD flag.
c   - overhaul using new keep, TABLEVARCOM.
c
c Mar 19 2018: check SKIP_ZPHOT option
c
c ------------------------------------

      IMPLICIT NONE
      INTEGER   FLAGCOV              ! (I)
      CHARACTER VARLIST*(*)          ! (O)
      INTEGER   LENLIST, LENPKMJD    ! (O)

c local args


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT.         PARNAME_STORE  is here inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


      INTEGER IPAR1, IPAR2,  LENNAME, LEN1, LEN2
      character ctmp*60, NAM1*40, NAM2*40
      LOGICAL SKIP_ZPHOT

C -------------------- BEGIN ----------------

      LENLIST  = 0
      LENPKMJD = 0

      NCOV_TBL = 0  ;  NCOV_TBL_PKMJD = 0
      SKIP_ZPHOT = (.not. WRTABLEFILE_ZPHOT)

      DO 21 ipar1 = IPAR_PEAKMJD, IPAR_MAX-1  ! start with PEAKMJD
         if ( .not. FLOATPAR(ipar1) ) GOTO 21
         if ( IPAR1 .EQ. IPAR_ZPHOT .and. SKIP_ZPHOT) goto 21

      DO 22 ipar2 = ipar1+1, IPAR_MAX
         if ( .not. FLOATPAR(ipar2) ) GOTO 22
         if ( IPAR2 .EQ. IPAR_ZPHOT .and. SKIP_ZPHOT) goto 22

         NAM1 = PARNAME_STORE(ipar1) ; LEN1 = INDEX(NAM1,' ') - 1
         NAM2 = PARNAME_STORE(ipar2) ; LEN2 = INDEX(NAM2,' ') - 1

         if ( NAM1(1:5) .EQ. 'BIDON' ) GOTO 22
         if ( NAM2(1:5) .EQ. 'BIDON' ) GOTO 22
         if ( NAM2(1:5) .EQ. 'PKMJD' ) GOTO 22

         IF ( FLAGCOV .EQ. 1 ) THEN
            write(ctmp,30) 'REDCOV', NAM1(1:LEN1), NAM2(1:LEN2)
         ELSE
            write(ctmp,30) 'COV',    NAM1(1:LEN1), NAM2(1:LEN2)
         ENDIF

30       format( A, '_', A, '_', A )

         LENNAME   = INDEX(Ctmp,' ') - 1
         LENLIST   = INDEX(VARLIST,' ') - 1
         NCOV_TBL  = NCOV_TBL + 1
         IPAR_TBL_COV(1,NCOV_TBL) = IPAR1
         IPAR_TBL_COV(2,NCOV_TBL) = IPAR2

         if ( NCOV_TBL .EQ. 1 ) then
            VARLIST = CTMP(1:LENNAME) // ':F'
         else
            VARLIST = VARLIST(1:LENLIST) // ',' //
     &           CTMP(1:LENNAME) // ':F'
         endif

         if ( IPAR1 .EQ. IPAR_PEAKMJD ) then
            NCOV_TBL_PKMJD = NCOV_TBL_PKMJD + 1
            LENPKMJD = INDEX(VARLIST,' ') - 1
         endif

22    CONTINUE
21    CONTINUE

      LENLIST = INDEX(VARLIST,' ') - 1

      RETURN
      END   ! end of TABLE_VARLIST_COV


C ===================================================
CDECK  ID>,  TABLE_SNSPEC_SALT2. 
      SUBROUTINE TABLE_SNSPEC_SALT2(isn)
c
c Prepare table for SALT2 spectra computed from LC fit params.
c
c Mar 21 2022: compute TBLSPEC_MAG_MODEL[_ERR] for each band and MJD
c
c -------------------------------
      IMPLICIT NONE
      INTEGER   ISN   ! 0->init, otherwise fill

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


      INTEGER ID, i, ep, LENNAME, LENFMT
      INTEGER IFILT, IFILTOBS, IFILTOBS_TMP
      REAL    Tobs, z, x0, x1, c, MWEBV
      REAL*8  FLUX8, FLUXERR8, MAG8, MAGERR8, KCOR8
      CHARACTER NAME*40, TEXTFMT*20, TEXTFMT_forC*20

c function
      INTEGER  getSpec_band_SALT2
      EXTERNAL getSpec_band_SALT2
c ----------------- BEGIN ------------------------

      ID = IDTABLE_MODELSPEC

c ----------------------------------

      IF ( ISN .EQ. 0 ) THEN

         NAME    = 'SPECTRA' // char(0)
         LENNAME  = INDEX(NAME,   ' ') - 1

         TEXTFMT  = TEXTFORMAT_TABLE(ITABLE_FITRES)
         LENFMT   = INDEX(TEXTFMT,' ') - 1
         TEXTFMT_forC = TEXTFMT(1:LENFMT) // char(0)

         CALL SNTABLE_CREATE(ID,NAME,TEXTFMT_forC, LENNAME,LENFMT)  ! C fun

         CALL INIT_TABLE_SNSPECVAR(ID, 'SNSPEC' )

        RETURN
      ENDIF

c ------------------------------------
c  fill table

c   terminate strings for C table-functions (snana.car routine)
      CALL TABLE_STRING_TERMINATION(+1)

      DO 400 i = 1, NFITDATA + NFITDATA_REJECT
          ep   = EPLIST_FIT(i)
          IFILTOBS = I4EP_ALL(ep,IEP_IFILT_OBS)

          TBLSPEC_MJD         = R4EP_ALL(ep,JEP_MJD) + SNGL(MJDOFF)
          TBLSPEC8_MJD              = R8EP_MJD(i)  ! note different index
          TBLSPEC_TREST             = R4EP_ALL(ep,JEP_TREST)
          TBLSPEC_TOBS              = R4EP_ALL(ep,JEP_TOBS)
          TBLSPEC_LAMREST           = R4EP_ALL(ep,JEP_LAMREST)
          TBLSPEC_IFILTOBS          = IFILTOBS
          TBLSPEC_CCDNUM            = I4EP_ALL(ep,IEP_CCDNUM)
          TBLSPEC_IMGNUM            = I4EP_ALL(ep,IEP_IMGNUM)
          TBLSPEC_FLUXCAL_DATA      = R4EP_ALL(ep,JEP_DATAFLUX)
          TBLSPEC_FLUXCAL_DATA_ERR  = R4EP_ALL(ep,JEP_DATAFLUX_ERR)
          TBLSPEC_FLUXCAL_MODEL     = R4EP_ALL(ep,JEP_MODELFLUX)
          TBLSPEC_FLUXCAL_MODEL_ERR = R4EP_ALL(ep,JEP_MODELFLUX_ERR)
          TBLSPEC_FIELD             = SNLC_FIELD(ep)
          TBLSPEC_CFILT             =
     &        filtdef_string(IFILTOBS:IFILTOBS) // char(0)

c Mar21 2022: compute model mag for every band at every MJD
          DO ifilt = 1, NFILTDEF_SURVEY
            ifiltobs_tmp = IFILTDEF_MAP_SURVEY(ifilt)
            CALL MODELMAG_CALC(IFILTOBS_TMP, 'OBS', TBLSPEC8_MJD,
     &          FLUX8, FLUXERR8, MAG8, MAGERR8, KCOR8 )
            TBLSPEC_MAG_MODEL(ifiltobs_tmp)     = sngl(MAG8)
            TBLSPEC_MAG_MODEL_ERR(ifiltobs_tmp) = sngl(MAGERR8)
          ENDDO

          Tobs  = TBLSPEC_TOBS
          z     = SNLC_REDSHIFT
          x0    = LCVAL_STORE(IPAR_x0)
          x1    = LCVAL_STORE(IPAR_SHAPE)
          c     = LCVAL_STORE(IPAR_COLOR)
          MWEBV = SNLC_MWEBV

          NBLAM_TBLSPEC =
     &      getSpec_band_SALT2(IFILTOBS, Tobs,    ! (I)
     &      z, x0, x1, c, MWEBV,                  ! (I)
     &      TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST )   ! (O)


          IF ( NBLAM_TBLSPEC > MXLAM_TBLSPEC ) THEN
            write(C1ERR,661) NBLAM_TBLSPEC, MXLAM_TBLSPEC
661         format('NBLAM=',I5,' exceeds bound of ', I5)
            c2err = 'Check MXLAM_TBLSPEC'
            CALL MADABORT('TABLE_SNSPEC_SALT2', C1ERR, C2ERR)
          ENDIF

          IF ( NBLAM_TBLSPEC > 0 ) THEN
             CALL SNTABLE_FILL(ID)  ! generic C function
          ENDIF

400   CONTINUE

      CALL TABLE_STRING_TERMINATION(-1)  ! remove termination

c ------------------------------------

      RETURN
      END  ! TABLE_SNSPEC_SALT2

C =====================================
CDECK  ID>,  TBSPECVAR. 
      SUBROUTINE INIT_TABLE_SNSPECVAR(ID,BLOCK)
c
c Created Nov 18 2016
c
c Initialize variables to store SALT2 spectrum for each epoch.
c Store epoch variables as scalars; e.g., MJD, TOBS, FLUXCAL.
c Store spectrum as vector array: LAMLIST and FLUXLIST.
c
c Initial use is that spectra are needed for chromatic
c corrections for each epoch (for DES).
c
c Call generic function SNTABLE_ADDCOL() that loads a table
c for each selected format: CERNLIB, ROOT, HDF5 ...
c
c Mar 21 2022: load all model mags for each obs.
c
c --------------

      IMPLICIT NONE
      INTEGER   ID          ! (I) table id
      CHARACTER BLOCK*(*)   ! (I) name of BLOCK

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK


C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,USRTAGCM. inserted below by ypatchy. 

      INTEGER MXUSERTAG
      PARAMETER ( MXUSERTAG = 1000 ) ! max number of user tags

      INTEGER
     &   N_USERTAGS           ! number of tags in USERTAGS_FILE
     &  ,USERTAG_VALUELIST(MXUSERTAG)  ! list of user tags
     &  ,USERTAG                   ! USERTAG value  for current SN

      BYTE
     &   USERTAG_USED(MXUSERTAG)   ! mark when each USERTAG is used

      CHARACTER
     &   USERTAG_CCIDLIST(MXUSERTAG)*(MXCHAR_CCID)  ! list of CCID

      COMMON / USERTAGCOM /
     &   N_USERTAGS, USERTAG_VALUELIST, USERTAG_CCIDLIST
     &  ,USERTAG, USERTAG_USED



C +CDE,TABLEVARCOM. inserted below by ypatchy. 

c Created May 2014
c Misc arrays used to initialize and fill FITRES table(s).
c These arrays either don't exist elsewhere (e..g, REDUCED
c covariance), or they replace existing arrays with BIDON
c elements removed; e.g., SNRMAX-list with unused filters
c excluded.

      INTEGER MXCOV_TBL
      PARAMETER (MXCOV_TBL = IPAR_MAX*(IPAR_MAX-1)/2 ) ! off-diags only

      REAL
     &   TBL_REDCOV(MXCOV_TBL)         ! only fited params
     &  ,TBL_COV(MXCOV_TBL)            ! idem
     &  ,TBL_XTMW(MXFILT_ALL)          ! only fitted filters
     &  ,TBL_SNRMAX(MXFILT_ALL)        ! idem

      INTEGER
     &   NCOV_TBL         ! size of REDCOV,COV arrays
     &  ,NCOV_TBL_PKMJD   ! first NCOV_PKMD elements have PKMJD element
     &  ,IPAR_TBL_COV(2,MXCOV_TBL)   ! list if IPARs for COV

c variables to define subset of fitted bands;

      INTEGER
     &   NFILTOBS_TABLE                  ! for ntuple
     &  ,IFILTOBS_MAP_TABLE(MXFILT_OBS)  ! ifilt_obs vs. sparse index
     &  ,IFILT_MAP_TABLE(MXFILT_OBS)     ! ifilt vs. sparse index

      CHARACTER SURVEY_FILTERS_TABLE*100  ! list of surveys filters to plot

c variables for SPECTRA table (Nov 2016)
      INTEGER    MXLAM_TBLSPEC, NBLAM_TBLSPEC, TBLSPEC_IFILTOBS
      INTEGER    TBLSPEC_CCDNUM, TBLSPEC_IMGNUM  ! Oct 2021
      PARAMETER ( MXLAM_TBLSPEC = 1000 )
      CHARACTER  TBLSPEC_CFILT*4, TBLSPEC_FIELD*(MXCHAR_FIELDNAME)
      REAL
     &   TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS, TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL(MXFILT_OBS)
     &  ,TBLSPEC_MAG_MODEL_ERR(MXFILT_OBS)
     &  ,TBLSPEC_LAMLIST(MXLAM_TBLSPEC)
     &  ,TBLSPEC_FLUXLIST(MXLAM_TBLSPEC)
      REAL*8 TBLSPEC8_MJD

c - - - - - -

      COMMON / TABLEVARCOM4 /
     &   TBL_REDCOV, TBL_COV, TBL_XTMW, TBL_SNRMAX
     &  ,NCOV_TBL, NCOV_TBL_PKMJD, IPAR_TBL_COV
c
     &  ,NFILTOBS_TABLE, IFILTOBS_MAP_TABLE, IFILT_MAP_TABLE
     &  ,SURVEY_FILTERS_TABLE
c
     &  ,NBLAM_TBLSPEC, TBLSPEC_IFILTOBS, TBLSPEC_FIELD
     &  ,TBLSPEC_CCDNUM, TBLSPEC_IMGNUM
     &  ,TBLSPEC_CFILT, TBLSPEC_MJD, TBLSPEC_TREST, TBLSPEC_TOBS
     &  ,TBLSPEC_LAMREST
     &  ,TBLSPEC_FLUXCAL_DATA,  TBLSPEC_FLUXCAL_DATA_ERR
     &  ,TBLSPEC_FLUXCAL_MODEL, TBLSPEC_FLUXCAL_MODEL_ERR
     &  ,TBLSPEC_MAG_MODEL, TBLSPEC_MAG_MODEL_ERR
     &  ,TBLSPEC_LAMLIST, TBLSPEC_FLUXLIST

      COMMON / TABLEVARCOM8 / TBLSPEC8_MJD


C +CDE,VMAXCOM. inserted below by ypatchy. 

c Created Jun 2013 by R.K.

c Examples for OPT_VMAX
c  OPT_VMAX = 2 -> use obs for mag, peak for Zmax
c  OPT_VMAX = 3 -> use peak for both mag and Zmax


      INTEGER
     &  MXFILT_VMAX
     & ,OPTBIT_MAG    ! Zmax at epoch of max obs brightness
     & ,OPTBIT_ZMAX
     & ,OPTBIT_VERBOSE

      REAL*8  MAGDIF_CONVERGE

      PARAMETER (
     &   MXFILT_VMAX   = 5
     &  ,OPTBIT_MAG    = 0  ! bit0 off/on -> mag at best-fit obs/peak
     &  ,OPTBIT_ZMAX   = 1  ! bit1 off/on -> zmax from best-fot obs/peak
     &  ,OPTBIT_VERBOSE = 7 ! bit7(128) -> verbose printout
     &  ,MAGDIF_CONVERGE = 0.001 ! stop when |mag(zmax)-MAGLIM| < CONVERGE
     &     )

      INTEGER
     &   NFILT_VMAX   !Number of obs filters to compute Zmax/Vmax
     &  ,IFILTOBS_LIST_VMAX(MXFILT_VMAX) ! sparse list

      REAL
     &   MAGLIM_LIST_VMAX(MXFILT_VMAX)
     &  ,TREST_LIST_VMAX(MXFILT_VMAX)
     &  ,MAG_LIST_VMAX(MXFILT_VMAX)
     &  ,Z_LIST_VMAX(MXFILT_VMAX)
     &  ,VOL_LIST_VMAX(MXFILT_VMAX)

      INTEGER NEP_LIST_VMAX(MXFILT_VMAX)

      CHARACTER FILTLIST_VMAX*20

      COMMON/ VMAXCOM /
     &    NFILT_VMAX, IFILTOBS_LIST_VMAX
     &   ,FILTLIST_VMAX, MAGLIM_LIST_VMAX
     &   ,TREST_LIST_VMAX, MAG_LIST_VMAX, Z_LIST_VMAX, VOL_LIST_VMAX
     &   ,NEP_LIST_VMAX

C ===================================

      INTEGER
     &    IFILT, IFILT_OBS, USE4TEXT
     &   ,LENLIST, LENNAME, LENBLOCK, LENPACK

      CHARACTER VARNAME*60, CBLOCK*40, CNFIT*20, CFILT*2

      EXTERNAL
     &     SNTABLE_ADDCOL_int
     &    ,SNTABLE_ADDCOL_flr
     &    ,SNTABLE_ADDCOL_dbl
     &    ,SNTABLE_ADDCOL_str

C ---------------- BEGIN ------------

      write(6,10) BLOCK, ID
 10   format(T6,'Create BLOCK = ',A,'  for TABLE ID = ', I5)
      call flush(6)

      LENBLOCK = INDEX(BLOCK//' ',' ') - 1
      CBLOCK   = BLOCK(1:LENBLOCK) // char(0)

c - - - -
      VARNAME = 'CCID:C*20' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, SNLC_CCID, VARNAME, 1,
     &                   LENBLOCK, 20 )

      VARNAME = 'FIELD:C*20' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, TBLSPEC_FIELD, VARNAME, 1,
     &                   LENBLOCK, 20 )

      VARNAME = 'BAND:C*4' // char(0)
      CALL SNTABLE_ADDCOL_str(ID, CBLOCK, TBLSPEC_CFILT, VARNAME, 1,
     &                   LENBLOCK, 4 )

      VARNAME = 'CCDNUM:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, TBLSPEC_CCDNUM, VARNAME, 1,
     &                   LENBLOCK, 20 )

      VARNAME = 'IMGNUM:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, TBLSPEC_IMGNUM, VARNAME, 1,
     &                   LENBLOCK, 20 )

      VARNAME = 'IFILTOBS:I' // char(0)
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, TBLSPEC_IFILTOBS, VARNAME, 1,
     &                   LENBLOCK, 20 )

      VARNAME = 'MJD:D' // char(0)
      CALL SNTABLE_ADDCOL_dbl(ID, CBLOCK, TBLSPEC8_MJD, VARNAME, 1,
     &                   LENBLOCK, 20 )

      VARNAME = 'TREST:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBLSPEC_TREST,
     &             VARNAME, 1,      LENBLOCK, 20 )

      VARNAME = 'LAMREST:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBLSPEC_LAMREST,
     &             VARNAME, 1,      LENBLOCK, 20 )

      VARNAME = 'FLUXCAL_DATA:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBLSPEC_FLUXCAL_DATA,
     &               VARNAME, 1,    LENBLOCK, 20 )

      VARNAME = 'FLUXCAL_DATA_ERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK,TBLSPEC_FLUXCAL_DATA_ERR,
     &              VARNAME,1,     LENBLOCK, 20 )

      VARNAME = 'FLUXCAL_MODEL:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBLSPEC_FLUXCAL_MODEL,
     &            VARNAME, 1, LENBLOCK, 20 )

      VARNAME = 'FLUXCAL_MODEL_ERR:F' // char(0)
      CALL SNTABLE_ADDCOL_flt(ID, CBLOCK, TBLSPEC_FLUXCAL_MODEL_ERR,
     &            VARNAME, 1, LENBLOCK, 20 )

c - - - - -
c Mar 21 2022: write model mag for all bands at each obs
c   initial use is for DCR correction in DES.

      DO 20 ifilt  = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt     = FILTDEF_STRING(ifilt_obs:ifilt_obs)
         VARNAME   = 'MAG_MODEL_' // cfilt(1:1) // ':F' // char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK,
     &       TBLSPEC_MAG_MODEL(ifilt_obs),
     &       VARNAME, 1, LENBLOCK, 20 )
20    CONTINUE

      DO 21 ifilt  = 1, NFILTDEF_SURVEY
         ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
         cfilt     = FILTDEF_STRING(ifilt_obs:ifilt_obs)
         VARNAME   = 'MAG_MODEL_ERR_' // cfilt(1:1) // ':F'//char(0)
         CALL SNTABLE_ADDCOL_flt(ID, CBLOCK,
     &       TBLSPEC_MAG_MODEL_ERR(ifilt_obs),
     &       VARNAME, 1, LENBLOCK, 20 )
21    CONTINUE

c - - - - -
      write(CNFIT,15) MXLAM_TBLSPEC
15    format('NBLAM[',I4.4,']' )  ! no spaces or commas in string
      VARNAME = CNFIT(1:11)  // char(0)  ! Num lambda bins
      CALL SNTABLE_ADDCOL_int(ID, CBLOCK, NBLAM_TBLSPEC,
     &     VARNAME, 0, LENBLOCK, 20)

      VARNAME = 'SPEC_LAMLIST(NBLAM):F'  // char(0)   ! wavelength list
      CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, TBLSPEC_LAMLIST(1),
     &        VARNAME, 0, LENBLOCK, 20)

      VARNAME = 'SPEC_FLUXLIST(NBLAM):F'  // char(0)   ! spec-fluxList
      CALL SNTABLE_ADDCOL_flt(ID,CBLOCK, TBLSPEC_FLUXLIST(1),
     &        VARNAME, 0, LENBLOCK, 20)

      RETURN
      END     ! INIT_TABLE_SNSPECVAR

C ===================================================
CDECK  ID>,  FITPAR_NEARNBR_APPLY. 
      SUBROUTINE FITPAR_NEARNBR_APPLY

C
C Jun 2013
C shell to call NEARNBR_LOADVAL and NEARNBR_APPLY
c Can be used for both training and apply mode, but here it
c is used only for training mode.
c
c Apr 23 2014: call IPAR = IPAR_PARNAME_STORE(VARNAME)
c              to associate each NN-sepmax variable with snana variable.
c              Replaces original hard-wired IPAR_LIST.
c
c Jan 18 2016: check NN_ITYPE_FIX
c Oct  7 2016: pass CCID to NEARNBR_LOADVAL
c
C ----------

      IMPLICIT NONE


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM. inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,NNCOM. inserted below by ypatchy. 

c    *** LEGACY ***
c Created Apr 2013 for Nearest Neighbor method.
c Define namelist inputs so that main snana job can
c check NN option and call init routines in sntools_nearnbr.c .

      INTEGER  NNFLAG_IGNORE,  NNFLAG_TRAIN, NNFLAG_APPLY, NN_MXVAR
      INTEGER  NN_MXTYPE
      PARAMETER ( NNFLAG_IGNORE=0, NNFLAG_TRAIN=1,  NNFLAG_APPLY=2)
      PARAMETER ( NN_MXVAR=10, NN_MXTYPE=10 )
      INTEGER  FLAG_NEARNBR

      CHARACTER
     &   NEARNBR_TRAINFILE_PATH*(MXCHAR_FILENAME)
     &  ,NEARNBR_TRAINFILE_LIST*(MXCHAR_FILENAME)  ! training set file
     &  ,NEARNBR_SEPMAX_VARDEF*(MXCHAR_FILENAME)  ! list of 'VAR min max bin'
     &  ,NEARNBR_SEPMAX_VARNAME(NN_MXVAR)*20   ! list of varnames
     &  ,NEARNBR_SEPMAX_IGNORE*40        ! list of VAR to IGNORE
     &  ,NEARNBR_TRUETYPE_VARNAME*60

      LOGICAL NEARNBR_TRAIN_ODDEVEN ! odd SNID from ref; even from train

      INTEGER
     &   NN_ITYPE_FIX       ! fix NN_ITYPE for spec-confirmed sample
     &  ,NN_ITYPE_SNIA      ! NN type for SNIa

c results
      INTEGER
     &   NN_ITYPE, NN_NCELL
     &  ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A

      REAL
     &   NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC
     &  ,NEARNBR_TRAINFILE_SCALE_NON1A

      COMMON / NNCOM /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF,  NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_SEPMAX_VARNAME
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa
     &   ,NNSUM_UNKNOWN, NNSUM_IA, NNSUM_NON1A
c results
     &   ,FLAG_NEARNBR
     &   ,NN_ITYPE, NN_NCELL, NN_PROB_Ia, NN_PROB_II, NN_PROB_IBC

      NAMELIST / NNINP /
     &    NEARNBR_TRAINFILE_PATH, NEARNBR_TRAINFILE_LIST
     &   ,NEARNBR_TRAINFILE_SCALE_NON1A
     &   ,NEARNBR_SEPMAX_VARDEF, NEARNBR_SEPMAX_IGNORE
     &   ,NEARNBR_TRUETYPE_VARNAME, NEARNBR_TRAIN_ODDEVEN
     &   ,NN_ITYPE_FIX, NN_ITYPE_SNIa


C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      REAL*8    DVAL, MAGVAL, MAGERR
      INTEGER   LV, i, IPAR, IPAR_ABS
      CHARACTER CCID_forC*(MXCHAR_CCID)
      CHARACTER VARNAME_forC*80, tmpName*80, FNAM*20
      CHARACTER VARNAME*80

c results
      INTEGER ITYPE, ITYPE_BEST, NCELL_TOT, NCELL, NTYPE
      INTEGER
     &   ITYPE_LIST(NN_MXTYPE)
     &  ,NCELL_TRAIN_LIST(NN_MXTYPE)

      REAL XCELL_TRAIN, XNTOT_TRAIN

c function
      INTEGER IPAR_PARNAME_STORE

C -------------- BEGIN -----------------

      NN_ITYPE = -9
      NN_NCELL =  0

      CCID_forC = SNLC_CCID(1:ISNLC_LENCCID)//char(0)

c check option to fix NN_ITYPE for spec-confirmed sample so that
c output table has NN info to match that of photoID table
      IF ( NN_ITYPE_FIX .GE. 0 ) THEN
         NN_ITYPE     = NN_ITYPE_FIX
         NN_NCELL     = 0
         RETURN
      ENDIF

c ----------

      IF ( NVAR_NEARNBR .EQ. 0 ) RETURN

      FNAM = 'FITPAR_NEARNBR_APPLY'

      DO 30 i = 1, NVAR_NEARNBR
         ! get snlc_fit IPAR  index for this NN variable index
         VARNAME  = NEARNBR_SEPMAX_VARNAME(i)
         IPAR     = IPAR_PARNAME_STORE(VARNAME)
         IPAR_ABS = abs(IPAR)

         IF ( IPAR_ABS .EQ. 0  .or. IPAR_ABS > MXFITPAR ) THEN
            write(c1err,661) IPAR, i, VARNAME
 661        format('Invalid IPAR = ', I4, '  for i=',I2, '  = ', A8)
            c2err = 'Something is messed up.'
            CALL MADABORT(FNAM, c1err, c2err )
         ENDIF

c translate snana parname of 'REDSHIFT' to 'z', unless photoz fit.
         tmpName = VARNAME   ! xxxx PARNAME_STORE(IPAR_ABS)
         IF ( IPAR_ABS .EQ. IPAR_zPHOT ) THEN
            IF ( .NOT. DOFIT_PHOTOZ ) tmpName = 'z'
         ENDIF

         LV = INDEX(tmpName,' ') - 1
         VARNAME_forC = tmpName(1:LV) // char(0)

         IF ( IPAR > 0 ) THEN
            DVAL = LCVAL_STORE(IPAR_ABS)
         ELSE
            DVAL = LCERR_STORE(IPAR_ABS)
         ENDIF

c xxxxxxxxxxxxxxxxxxxxxx
c         print*,' xxx IPAR=', IPAR,'  VARNAME=', VARNAME_forC(1:LV),
c     &            '  DVAL=', SNGL(DVAL)
c xxxxxxxxxxxxxxxxxxxxxx

         CALL NEARNBR_LOADVAL(CCID_forC, VARNAME_forC, DVAL,
     &       ISNLC_LENCCID, LV )
 30   CONTINUE

c --------------------------------------------------
c load true sim-type only when doing the training.

      IF (  FLAG_NEARNBR == NNFLAG_TRAIN ) THEN
         tmpName      = NEARNBR_TRUETYPE_VARNAME
         LV           = index(tmpName,' ') - 1
         VARNAME_forC = tmpName(1:LV) // char(0)

         IF ( tmpName .EQ. 'SIM_TYPE_INDEX' ) THEN
            DVAL    = DBLE(SIM_GENTYPE)
         ELSE IF ( tmpName .EQ. 'SIM_NON1A' ) THEN ! legacy name
            DVAL  = DBLE(SIM_TEMPLATE_INDEX)
         ELSE IF ( tmpName .EQ. 'SIM_TEMPLATE_INDEX' ) THEN  ! 7.31.2018
            DVAL  = DBLE(SIM_TEMPLATE_INDEX)
         ELSE
            c1err = 'Unrecognized true-type index: '
            c2err = tmpName
            CALL MADABORT(FNAM, c1err, c2err )
         ENDIF

         CALL NEARNBR_LOADVAL(CCID_forC, VARNAME_forC, DVAL,
     &        ISNLC_LENCCID, LV )
      ENDIF

c -------------------------------------------
c run the analysis.
      CALL  NEARNBR_APPLY(CCID_forC, ISNLC_LENCCID)

c ---------------------
c Apr 7 2014
      CALL NEARNBR_GETRESULTS(CCID_forC, ITYPE_BEST,
     &      NTYPE, ITYPE_LIST, NCELL_TRAIN_LIST, ISNLC_LENCCID )

      XNTOT_TRAIN  = 0.0
      DO  i = 1, NTYPE
         XNTOT_TRAIN = XNTOT_TRAIN + float(NCELL_TRAIN_LIST(i))
      ENDDO

      NN_ITYPE     = ITYPE_BEST        ! most probably ITYPE
      NN_NCELL     = INT(XNTOT_TRAIN)

c apply user-ITYPE ranges to determine NN_PROB_XX
      NN_PROB_IA  = 0.0
      NN_PROB_II  = 0.0
      NN_PROB_IBC = 0.0

c increment how many for each ITYPE_BEST
      IF ( ITYPE_BEST == 1 ) THEN
          NNSUM_IA = NNSUM_IA + 1
      ELSE IF ( ITYPE_BEST .GE. 0 ) THEN
          NNSUM_NON1A = NNSUM_NON1A + 1
      ELSE
          NNSUM_UNKNOWN = NNSUM_UNKNOWN + 1
          RETURN
      ENDIF

c - - - -  - - - - - - - -
      DO 202 i = 1, NTYPE
         ITYPE = ITYPE_LIST(i)
         NCELL = NCELL_TRAIN_LIST(i)
         XCELL_TRAIN = FLOAT( NCELL_TRAIN_LIST(i) )

         if ( ITYPE == NN_ITYPE_SNIA ) THEN
              NN_PROB_IA  = NN_PROB_IA    + XCELL_TRAIN
          endif

c          write(6,333) ITYPE, NCELL, NN_NCELL, int(NN_PROB_IA)
333       format(' xxx ITYPE=',I3, 3x,'NCELL=',I4,'/',I4,
     &          3x,'NN_IA=',I4)
202   CONTINUE

      IF( XNTOT_TRAIN > 0.0 ) THEN
         NN_PROB_IA   = NN_PROB_IA  / XNTOT_TRAIN
      ENDIF

      RETURN
      END      ! end FITPAR_NEARNBR_APPLY

C ===============================
CDECK  ID>,  IPAR_PARNAME_STORE. 
      INTEGER FUNCTION IPAR_PARNAME_STORE(VARNAME)

C Apr 23 2014, R. Kessler
C for input string VARNAME, return IPAR such that
c    VARNAME = PARNAME_STORE(IPAR).
c If VARNAME has 'ERR' at the end, then return negative IPAR value
c
c Nov 14 2014: fix bug to allow zPHOT as well as z.
c Jan 02 2016: check for 'ERR' extension

      IMPLICIT NONE
      CHARACTER VARNAME*(*)  ! (I) variable name to analyze

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )



C +CDE,FITRESTCOM. inserted below by ypatchy. 


C +CDE,ALLFILTCOM. inserted below by ypatchy. 
c
c Mar 2013: generic variables to store ALL-FILTER results
c           before doing more specialize fits such as rest-frame mags.

      INTEGER
     &   NFIT_ITERATION_ALLFILT
     &  ,NOBS_ALLFILT           ! store NFILT_OBS using all filters

      CHARACTER
     &   ALLFILTLIST_FIT*(MXFILT_ALL)    ! original filter list
      LOGICAL
     &   USE_ALLFILT(MXFILT_ALL)

      REAL
     &   FITVAL_ALLFILT(MXFITPAR)
     &  ,FITERR_ALLFILT(MXFITPAR)

      COMMON / ALLFILTCOM / NFIT_ITERATION_ALLFILT
     &  ,USE_ALLFILT, NOBS_ALLFILT,  ALLFILTLIST_FIT
     &  ,FITVAL_ALLFILT, FITERR_ALLFILT



c for option to fit peakMag in rest-frame filter

      INTEGER MXFILT_FITRESTMAG, NFIT_ITER_FITRESTMAG
      PARAMETER (
     &   MXFILT_FITRESTMAG    = 10
     &  ,NFIT_ITER_FITRESTMAG =  1  ! Number of fit-iters per rest-filter
     &     )

      INTEGER
     &   NFILTDEF_FITRESTMAG
     &  ,IFILTDEF_FITRESTMAG(MXFILT_FITRESTMAG)
     &  ,IFILTDEF_ITER_FITRESTMAG(MXITER)    ! IFILTDEF vs. ITER
     &  ,IFILTSP_ITER_FITRESTMAG(MXITER)     ! sparse IFILT vs. ITER
     &  ,ITERLAST_FITRESTMAG(MXFILT_FITRESTMAG) ! last iteration vs. IFILTSP
     &  ,NFILTDEF_SURVEY_ORIG
     &  ,NLCPLOT_FITRESTMAG
     &  ,IFILTOBS_BRACKET(MXFILT_FITRESTMAG)
     &  ,IPAROFF_FITRESTMAG  ! IPAR offset for LCVAL_STORE

      REAL
     &   FITRESTMAG(MXFILT_FITRESTMAG)         ! calculated restmag value
     &  ,FITRESTMAG_ERR(MXFILT_FITRESTMAG)     ! error on above

      COMMON / FITRESTMAGCOM / NFILTDEF_SURVEY_ORIG
     &  ,NFILTDEF_FITRESTMAG, IFILTDEF_FITRESTMAG
     &  ,IFILTDEF_ITER_FITRESTMAG, IFILTSP_ITER_FITRESTMAG
     &  ,ITERLAST_FITRESTMAG, FITRESTMAG, FITRESTMAG_ERR
     &  ,NLCPLOT_FITRESTMAG, IFILTOBS_BRACKET, IPAROFF_FITRESTMAG


      CHARACTER tmpName*40, cfilt*2, FNAM*20, VLOC*40
      INTEGER IPAR, ifilt, LENPAR, LENLOC
      LOGICAL ISERR

C ----------- BEGIN -----------

      IPAR = -99
      FNAM = 'IPAR_PARNAME_STORE'

c ------------------------------
c check for 'ERR' at the end
      ISERR  = .FALSE.
      LENPAR = INDEX(VARNAME,' ') - 1
      VLOC   = VARNAME
      IF ( LENPAR > 3 ) THEN
         IF ( VARNAME(LENPAR-2:LENPAR) .EQ. 'ERR' ) then
           ISERR = .TRUE.
           VLOC  = VARNAME(1:LENPAR-3)
         ENDIF
      ENDIF

      LENLOC = INDEX(VLOC,' ') - 1

c ------------------------------
      IF ( VLOC(1:LENLOC) .EQ. 'z' ) THEN
         IPAR = IPAR_zPHOT  ! allow 'z' instead of longer 'REDSHIFT'
      ELSE IF ( VLOC(1:LENLOC) .EQ. PARNAME_STORE(IPAR_zPHOT) ) THEN
         IPAR = IPAR_zPHOT
      ELSE IF ( VLOC(1:LENLOC) .EQ. PARNAME_STORE(IPAR_COLOR) ) THEN
         IPAR = IPAR_COLOR
      ELSE IF ( VLOC(1:LENLOC) .EQ. PARNAME_STORE(IPAR_SHAPE) ) THEN
         IPAR = IPAR_SHAPE
      ELSE IF ( VLOC(1:3) .EQ. 'M0_' ) THEN

c      check FITRESTMAG variables
         DO ifilt    = 1, NFILTDEF_FITRESTMAG
            cfilt    = FILTLIST_FITRESTMAG(ifilt:ifilt)
            tmpName  = 'M0_' // cfilt
            if ( VARNAME .EQ. tmpName ) then
               IPAR = IPAROFF_FITRESTMAG + 2*ifilt-1 ! skip errors
            endif
         ENDDO
         IF ( IPAR < 0 ) then
            c1err = 'Cannot identify VARANME = ' // VARNAME
            c2err = 'Check NEARNBR options.'
            CALL MADABORT(FNAM, c1err, c2err )
         endif
      ELSE
         CALL PRINT_PREABORT_BANNER(FNAM//CHAR(0), 40)
         print*,'   LENPAR, LENLOC, ISERR = ', LENPAR, LENLOC, ISERR
         print*,'   VARNAME = ', VARNAME(1:20)
         print*,'   VARNAME(LENPAR-3:LENPAR) = ',
     &              VARNAME(LENPAR-3:LENPAR)
         print*,'   VLOC    = ', VLOC(1:20)

         c1err = 'Cannot determine IPAR for VARNAME='
     &             // VARNAME(1:12)
         c2err = 'Check NEANBR options.'
         CALL MADABORT(FNAM, c1err, c2err )
      ENDIF

      IF ( ISERR ) THEN
        IPAR_PARNAME_STORE = -IPAR
      ELSE
        IPAR_PARNAME_STORE = +IPAR
      ENDIF

      RETURN
      END  ! end of  IPAR_PARNAME_STORE


C =====================================================
CDECK  ID>,  HFUNMIN. 
      SUBROUTINE HFUNMIN()
c
c Oct 22, 2008
c
c Plot function (chi2) around minimum for each fit-parameter.
c Plot 2D functions of chi2 vs. filter, where filter=0
c corresponds to the data chi2 that excludes the prior,
c
c Useful namelist control variables
c
c   LPLOTCHI2 = T             ! global flag to call HFUNMIN
c   IPAR_PLOTCHI2     = 9     ! plot only this IPAR (default=all)
c   FILTLIST_DMPFCN   = 'r'   ! dump FCN for r
c   FILTLIST_DMPFUN   = 'r'   ! dump USRFUN for r and TREST_DMPFUN below
c   SCALE_PLOTCHI2    = 1.0   ! scale range to plot chi2
c   TREST_DMPFUN      = 12.07, 12.09
c
c
c Aug 31, 2009: check IPAR_PLOTCHI2 for option to plot chi2
c               for just one parameter.
c
c               If FILTLIST_DMPFCN[FUN] is set, then apply dump
c               only within +-10 bins of chi2 minimum.
c               See internal arrays LDMPFCN_PLOTCHI2
c               and LDMPFUN_PLOTCHI2.
c
c Jun 22, 2012:
c   Plot only filters used in fit so that hid=1 has correct
c   filter-list for generic snana#chi2nearmin macro.
c   See NFILT_OBS_USEFIT.
c
c Feb 6, 2013: replace hbook calls with SNHIST_XXX routines.
c
c ----------------------

      IMPLICIT NONE

c hard-wire  a few things
      INTEGER HOFF, NFITSIG, NBFITPAR
      PARAMETER (
     &    HOFF      = 2000  ! hbook offset
     &   ,NFITSIG   = 10    ! go out +-NSIG sigma from central value
     &   ,NBFITPAR  = 100   ! Number of fitpar bins to compute chi2
c     &   ,NBFITPAR  = 500   ! Number of fitpar bins to compute chi2
     &      )



C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNANAFIT. inserted below by ypatchy. 

c store fit results for use in snana
c define arrays used in fit.

      INTEGER MXFITPAR, MXFITSTORE

      PARAMETER (
     &   MXFITPAR    =  12    ! max number of fit parameters
     &  ,MXFITSTORE  =  800   ! max number of storage params
     &     )

      INTEGER
     &   NFITPAR(0:MXFILT_OBS)   ! Nfitpar for 0=all, or 'ifilt'
     &  ,NFITPAR_MN         ! Minuit NFITPAR includes NFIXPAR
     &  ,NFIXPAR            ! Number of fixed parameters (i.e, INISTP=0)
     &  ,NPLOTPAR            ! Number of extra FITVAL parameters to plot
     &  ,NEPOCH_ALL(0:MXFILT_OBS)    ! fit+rejected epochs per filter
     &  ,NEPOCH_FIT(0:MXFILT_OBS)    ! number of epochs fit per filter
     &  ,NEPOCH_REJECT(0:MXFILT_OBS) ! number of epochs rejected by fit
     &  ,NEPOCH_REJECT2          ! total rejected ep within TREST window
     &  ,ERRTYPE(MXFITPAR)  ! MINOS or PARAB
     &  ,PARPTR_CHI2
     &  ,PARPTR_IFILT_REST(MXFILT_ALL)
     &  ,PARPTR_FITRESTMAG

      DOUBLE PRECISION
     &   INIVAL(MXFITPAR)
     &  ,INISTP(MXFITPAR)
     &  ,INIBND(2,MXFITPAR)
c
     &  ,FITVAL(MXFITPAR,0:MXITER)
     &  ,FITERR(MXFITPAR,0:MXITER)
     &  ,FITERR_PLUS(MXFITPAR,MXITER)
     &  ,FITERR_MINUS(MXFITPAR,MXITER)
     &  ,FITERR_RATIO(MXFITPAR,MXITER)  ! abs(EPLUS/Eminus)
c
     &  ,FITCHI2_MIN   ! min chi2 after minimization
     &  ,FITCHI2_QUIT  ! quit FCN calc if chi2 exceeds this value
     &  ,SIMCHI2_CHEAT ! chi2 using exact sim values
     &  ,FITERRMAT_SPARSE(MXFITPAR,MXFITPAR)
     &  ,FITERRMAT(MXFITPAR,MXFITPAR)
     &  ,FITCORMAT(MXFITPAR,MXFITPAR)
c
     &  ,PDFVAL(MXFITPAR)
     &  ,PDFERR(MXFITPAR)
     &  ,PDFPROB2(MXFITSTORE)
     &  ,PDFERRMAT(MXFITPAR,MXFITPAR)
     &  ,PDFCORMAT(MXFITPAR,MXFITPAR)

c declare fit-storage arrays for all SN

      REAL
     &   FITVAL_STORE(MXFITSTORE)
     &  ,FITERR_STORE(MXFITSTORE)
     &  ,PDFVAL_STORE(MXFITSTORE)  ! from average over PDF integral
     &  ,PDFERR_STORE(MXFITSTORE)  !
     &  ,PDFPROB2_STORE(MXFITSTORE)  !
     &  ,LCVAL_STORE(MXFITSTORE)   !  either FITVAL or PDFVAL
     &  ,LCERR_STORE(MXFITSTORE)   !  either FITERR or PDFERR
     &  ,LCFRACERRDIF_STORE(MXFITSTORE)  ! frac change on last 2 iter
c
     &  ,LCCHI2_STORE(4)        !  1,2,3,4=> TOTAL,data,prior,sigma
     &  ,LCPROBCHI2_STORE(4)    !  idem for prob
     &  ,FITCHI2_STORE(4)       !  idem for fit minimum
     &  ,FITPROBCHI2_STORE(4)
c
     &  ,INIVAL_STORE(MXFITSTORE)  ! store all inital values
     &  ,SIMVAL_STORE(MXFITPAR)     ! sim values
c
     &  ,ERRMAX_BAD(MXFITPAR)     ! err < ERRMAX_BAD labelled bad
     &  ,MAG_XTMW_REF(MXFILT_ALL) ! ref MWXT mags subtracted from data
c
c ------ define FITANA_CUTWIN_XXX that depend on spec-vs-photoz fit
     &  ,FITANA_CUTWIN_TREST(2)
     &  ,FITANA_CUTWIN_TRESTMIN(2)
     &  ,FITANA_CUTWIN_TRESTMAX(2)
     &  ,FITANA_CUTWIN_TREST2(2)
     &  ,FITANA_CUTWIN_TGAPMAX(2)
     &  ,FITANA_CUTWIN_T0GAPMAX(2)
c ------ SNLC_XXX -> XXX_FIT re-evaluated after final fit
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TOBSMIN_FIT,  TOBSMAX_FIT
     &  ,TGAPMAX_FIT,  T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT(MXFILT_OBS)      ! sparse ordering
     &  ,SNRMAX_SORT_FIT(MXFILT_OBS)

      INTEGER
     &   ERRTYPE_STORE(MXFITPAR)  ! MINOS or PARABOLIC
     &  ,NERRTYPE(MXERRTYPE)      ! # params per error type
     &  ,NDOF_STORE(4)            ! 1,2,3 => TOTAL, DATA, PRIOR, SIGMA
     &  ,NDOF_PRIOR
     &  ,NCALL_INTEGPDF
     &  ,TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF
     &  ,TIMEAVG_INTEGPDF
c ---- ISNLC_XXX  -> XXX_FIT  re-evaluated after fitting
     &  ,NFILT_TRESTMIN_FIT
     &  ,NFILT_TRESTMAX_FIT
     &  ,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT    ! added Sep 30 2012
     &  ,NFILT_SNRMAX2_FIT   ! added Sep 20 2012
     &  ,MNSTAT_COV          ! ISTAT returned from MNSTAT: see minuit manual

      CHARACTER
     &   PARNAME_STORE(MXFITSTORE)*(MXCHAR_PARNAME)  ! stored parameter names
      INTEGER
     &   PAROPT_STORE(MXFITSTORE)  ! storage options for output

      LOGICAL
     &   FLOATPAR(MXFITPAR)   ! T => ipar is floated in fit
     &  ,USEPDF_MARG          ! T => use margin. pdf-avg instead of fit-values
     &  ,LREPEAT_ITER         ! internal flag for repeated iteration
     &  ,LREPEAT_MINOS        ! repeat entire fit with MINOS (May 2018)

      COMMON / SNANAFIT4 /
     &   NFITPAR_MN, NFITPAR, NFIXPAR, PARNAME_STORE, PAROPT_STORE
     &  ,NEPOCH_ALL, NEPOCH_FIT, NEPOCH_REJECT, NEPOCH_REJECT2
     &  ,NPLOTPAR, ERRTYPE, FLOATPAR, USEPDF_MARG
     &  ,PARPTR_CHI2, PARPTR_IFILT_REST, PARPTR_FITRESTMAG
     &  ,FITVAL_STORE, FITERR_STORE
     &  ,FITCHI2_STORE, FITPROBCHI2_STORE
     &  ,PDFVAL_STORE, PDFERR_STORE, PDFPROB2_STORE
     &  ,LCVAL_STORE,  LCERR_STORE, LCFRACERRDIF_STORE
     &  ,LCCHI2_STORE, LCPROBCHI2_STORE
     &  ,INIVAL_STORE
     &  ,ERRTYPE_STORE, NERRTYPE, ERRMAX_BAD
     &  ,NDOF_STORE, NDOF_PRIOR, SIMVAL_STORE
     &  ,NCALL_INTEGPDF, TIME_INTEGPDF
     &  ,TIMESUM_INTEGPDF, TIMEAVG_INTEGPDF
c
     &  ,FITANA_CUTWIN_TREST
     &  ,FITANA_CUTWIN_TRESTMIN, FITANA_CUTWIN_TRESTMAX
     &  ,FITANA_CUTWIN_TREST2
     &  ,FITANA_CUTWIN_TGAPMAX,  FITANA_CUTWIN_T0GAPMAX
     &  ,TRESTMIN_FIT, TRESTMAX_FIT, TRESTRANGE_FIT
     &  ,TobsMIN_FIT, TobsMAX_FIT, TGAPMAX_FIT, T0GAPMAX_FIT
     &  ,SNRMAX_FILT_FIT, SNRMAX_SORT_FIT
     &  ,NFILT_TRESTMIN_FIT,NFILT_TRESTMAX_FIT,NFILT_TREST2_FIT
     &  ,NFILT_SNRMAX_FIT,   NFILT_SNRMAX2_FIT
     &  ,LREPEAT_ITER, LREPEAT_MINOS,  MNSTAT_COV

      COMMON / SNANAFIT8 /
     &   INIVAL, INISTP, INIBND, FITVAL
     &  ,FITERR, FITERR_PLUS, FITERR_MINUS, FITERR_RATIO
     &  ,FITCHI2_MIN, FITCHI2_QUIT, SIMCHI2_CHEAT
     &  ,FITERRMAT_SPARSE, FITERRMAT, FITCORMAT
     &  ,PDFVAL, PDFERR, PDFPROB2, PDFERRMAT, PDFCORMAT
     &  ,MAG_XTMW_REF

C =============================================

C +CDE,SNFITCOM.   private fitter info inserted below by ypatchy. 


C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


C +CDE,SNFITVAR. inserted below by ypatchy. 

      INTEGER MXFIT_DATA
      PARAMETER ( MXFIT_DATA = 2000 ) ! -> 2000 on Mar 13 2024 (was 1500)

c variables used in fit.

      LOGICAL
     &   LBKSNINFO
     &  ,USESIM_FITPAR(IPAR_MAX)
     &  ,LOBS_FITMODEL, LREST_FITMODEL
     &  ,LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST   ! True if using MCMC init for photo-z

      INTEGER
     &   FITMODEL_INDEX              ! integer index for model to fit
     &  ,NSHAPEPAR                    ! 1 or 2
     &  ,NFITDOF(0:MXFILT_OBS)       ! # deg of freedom per filter (0=all)
     &  ,NFILT_FIT                   ! number of filters fitted
     &  ,ISTORE_ZPULL                ! storage index for Photoz Pull
     &  ,NFILT_MODEL                 ! # rest-filters in SN model
     &  ,IFILTMAP_MODEL(MXFILT_ALL)  ! spare map: ifilt_rest = (ifilt)
     &  ,IFILTINVMAP_MODEL(MXFILT_ALL) ! inverse map

c ------------
c NEW Jan 25 2014
c Define two sets of arrays:
c  1: _ALL stores all epochs using the fixed 'ep' index
c  2: _FIT stores only the epochs used in the fit; so each index
c     can change its location on the next iteration. This sparse
c     array is needed for SNLCPAK.
c
c Note that EPLIST_FIT is used in FCN to loop over only
c the epochs to be fit.
c
c Oct 15 2021: add IEP_CCDNUN, IEP_IMGNUM

      INTEGER MXVAR_R4, MXVAR_I4
      PARAMETER ( MXVAR_R4=60, MXVAR_I4=12 )

      REAL*4
     &   R4EP_ALL(MXFIT_DATA,MXVAR_R4)  !vs. absolute epoch; fixed each iter
     &  ,R4EP_FIT(MXFIT_DATA,MXVAR_R4)  !sparse subset in fit; changes each iter
     &  ,R4EP_LAST(MXFIT_DATA,MXVAR_R4) ! store R4EP_ALL for previous fit-iter

      INTEGER
     &   I4EP_ALL(MXFIT_DATA,MXVAR_I4)
     &  ,I4EP_FIT(MXFIT_DATA,MXVAR_I4)
     &  ,EPLIST_FIT(MXFIT_DATA)          ! ep-list for _FIT arrays

      CHARACTER
     &   BANDEP_ALL(MXFIT_DATA)*4  ! added July 2017
     &  ,BANDEP_FIT(MXFIT_DATA)*4

      COMMON / EPFITCOM4 / EPLIST_FIT
     &    ,R4EP_ALL, R4EP_FIT, I4EP_ALL, I4EP_FIT, R4EP_LAST
     &    ,BANDEP_ALL, BANDEP_FIT

c define index for each variable.

c variable indices for integer I4EP_
      INTEGER
     &   IEP_IMJD, IEP_EPOCH
     &  ,IEP_IFILT, IEP_IFILT_OBS, IEP_IFILT_REST1, IEP_IFILT_REST2
     &  ,IEP_REJECT, IEP_REJECT2
     &  ,IEP_CCDNUM, IEP_IMGNUM

c variable indices for real R4EP_
      INTEGER
     &   JEP_MJD, JEP_TOBS, JEP_TREST
     &  ,JEP_DATAFLUX,  JEP_DATAFLUX_ERR
     &  ,JEP_DATAMAG,   JEP_DATAMAG_ERR
     &  ,JEP_MODELFLUX, JEP_MODELFLUX_ERR
     &  ,JEP_MODELMAG,  JEP_MODELMAG_ERR
     &  ,JEP_FLUX_ERRTOT, JEP_RATIO, JEP_RATIO_ERR
     &  ,JEP_LAMREST, JEP_AVWARP, JEP_KCOR, JEP_KCOR_ERR
     &  ,JEP_DATAFLUX_REST, JEP_MODELMAG_REST
     &  ,JEP_FUDGEFLUX_ERR, JEP_FUDGE_MAXFRAC
     &  ,JEP_RESID, JEP_RESID_ERR, JEP_MAGDIF, JEP_DELCHI2
     &  ,JEP_XTHOST, JEP_MWXT, JEP_MWXT_MAGERR, JEP_MWXT_FLUXERR
     &  ,JEP_FPKRAT, JEP_FPKRATERR
     &  ,JEP_PSF, JEP_NEA, JEP_SKYSIG, JEP_SKYSIG_T
     &  ,JEP_ZP, JEP_ZPERR, JEP_GAIN, JEP_XPIX, JEP_YPIX, JEP_AREAFRAC
     &  ,JEP_SKYFLUXCAL, JEP_SBFLUXCAL, JEP_ERRTEST, JEP_ERRCALC
     &  ,JEP_PHOTPROB
     &  ,JEP_SIM_MAGREST, JEP_SIM_FLUXREST
     &  ,JEP_SIM_FLUXCAL, JEP_SIM_DELCHI2

      PARAMETER (
c for I4EP_XXX
     &   IEP_IMJD            = 1  ! for absolute IMJD index
     &  ,IEP_EPOCH           = 2  ! for absolute ep index
c
     &  ,IEP_IFILT           = 4  ! sparse survey filter index
     &  ,IEP_IFILT_OBS       = 5  ! absolute filter index
     &  ,IEP_IFILT_REST1     = 6  ! absolute filter index, nearest rest-filter
     &  ,IEP_IFILT_REST2     = 7  ! idem, 2nd nearest rest-frame filter
     &  ,IEP_REJECT          = 8  ! flag to reject epoch from fit
     &  ,IEP_REJECT2         = 9  ! rejected inside Trest window (Mar 2020)
     &  ,IEP_CCDNUM          = 10 ! CCD number
     &  ,IEP_IMGNUM          = 11 ! image number (e..g, EXPNUM, VISIT_ID)
c
c for R4EP_XXX
     &  ,JEP_MJD              = 1
     &  ,JEP_TOBS             = 2
     &  ,JEP_TREST            = 3
     &  ,JEP_DATAFLUX         = 4
     &  ,JEP_DATAFLUX_ERR     = 5
     &  ,JEP_DATAMAG          = 6
     &  ,JEP_DATAMAG_ERR      = 7
     &  ,JEP_MODELFLUX        = 8
     &  ,JEP_MODELFLUX_ERR    = 9
     &  ,JEP_MODELMAG         = 10
     &  ,JEP_MODELMAG_ERR     = 11
     &  ,JEP_FLUX_ERRTOT      = 12
     &  ,JEP_RATIO            = 13
     &  ,JEP_RATIO_ERR        = 14
     &  ,JEP_LAMREST          = 15
     &  ,JEP_AVWARP           = 16
     &  ,JEP_KCOR             = 17
     &  ,JEP_KCOR_ERR         = 18
     &  ,JEP_DATAFLUX_REST    = 19
     &  ,JEP_MODELMAG_REST    = 20
     &  ,JEP_FUDGEFLUX_ERR    = 21
     &  ,JEP_RESID            = 22
     &  ,JEP_RESID_ERR        = 23
     &  ,JEP_MAGDIF           = 24  ! mag(data) - mag(fitModel)
     &  ,JEP_DELCHI2          = 25
     &  ,JEP_XTHOST           = 26
     &  ,JEP_MWXT             = 27
     &  ,JEP_MWXT_MAGERR      = 28
     &  ,JEP_MWXT_FLUXERR     = 29
     &  ,JEP_FPKRAT           = 30
     &  ,JEP_FPKRATERR        = 31
     &  ,JEP_PSF           = 32
     &  ,JEP_NEA           = 33
     &  ,JEP_SKYSIG        = 34
     &  ,JEP_SKYSIG_T      = 35
     &  ,JEP_ZP            = 36
     &  ,JEP_ZPERR         = 37
     &  ,JEP_GAIN          = 38
     &  ,JEP_XPIX          = 39
     &  ,JEP_YPIX          = 40
     &  ,JEP_AREAFRAC      = 41
     &  ,JEP_SKYFLUXCAL    = 42
     &  ,JEP_SBFLUXCAL     = 43
     &  ,JEP_ERRTEST       = 44  ! ERRCALC/FLUXCAL_ERR
     &  ,JEP_ERRCALC       = 45  ! calculated error
     &  ,JEP_PHOTPROB      = 46
     &  ,JEP_SIM_MAGREST   = 47
     &  ,JEP_SIM_FLUXREST  = 48
     &  ,JEP_SIM_FLUXCAL   = 49  ! for LSIM_MAGOBS = T
     &  ,JEP_SIM_DELCHI2   = 50  ! chi2 from data-sim flux diff
     &  ,JEP_FUDGE_MAXFRAC = 51
     &     )

c EP_XXX refers to "IMJD" variables stored at end of fit.
c These arrays are defined to be passed for plotting.

      REAL
     &   FCN_FITCHI2(0:MXFILT_OBS)         ! FCN fit chi2 per filter (0=>sum)
     &  ,XNFITDOF(0:MXFILT_OBS)
     &  ,PEAKMAG_OBS_MODEL(MXFILT_ALL)         ! model peak mag (observer)
     &  ,PEAKMAG_OBS_MODEL_ERR(MXFILT_ALL)     ! error on above
     &  ,PEAKFLUX_OBS_MODEL(MXFILT_ALL)        ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_ERR(MXFILT_ALL)    ! model peak flux (observer)
     &  ,PEAKFLUX_OBS_MODEL_COR(MXFILT_ALL)    ! data/model correction
     &  ,PEAKMAG_REST_MODEL(MXFILT_ALL)        ! model peak mag (rest-frame)
     &  ,PEAKMAG_REST_MODEL_ERR(MXFILT_ALL)    ! error on above
     &  ,PEAK_KCOR_MODEL(MXFILT_ALL)           ! model Kcor at peak
c
     &  ,REDSHIFT_FIT   ! z used in fit: SNLC_REDSHIFT or SIM_REDSHIFT
     &  ,CUTWIN_FITPAR(2,IPAR_MAX)             ! used in fitter cuts
     &  ,CUTWIN_FITCOV(2,IPAR_MAX,IPAR_MAX)    ! idem, 9/2016
     &  ,CUTWIN_FITERRz1(2,IPAR_MAX)           ! cuts on sigma(fitPar)/(1+z)
c
     &  ,LC_FITCHI2(0:MXFILT_OBS)   ! min chi2 from fit
     &  ,LC_FITPROB(0:MXFILT_OBS)   ! prob from above
     &  ,LC_MARGCHI2(0:MXFILT_OBS)  ! chi2 from marginalized params
     &  ,LC_MARGPROB(0:MXFILT_OBS)  ! prob from above
c
     &  ,RESTLAMBDA_MODEL(2)   ! range defined by SN model
     &  ,RESTLAMBDA_USEFIT(2)  ! range actually used in fit (Nov 2012)

      LOGICAL
     &   USE_FITCOV  ! T=> use full covariance matrix in fit
     &  ,USE_FILT(0:MXFILT_ALL)  ! user-filter and it exists
     &  ,USE_LANDOLT_REST
     &  ,USE_LANDOLT_OBS

      INTEGER
     &   NFITDATA             ! number of fitted data points
     &  ,NFITDATA_REJECT      !  number rejected
     &  ,NFITDATA_TOTAL                 ! sum of above
     &  ,IFITDATA_USRFUN
     &  ,I4BAND_EP_NEARPEAK(MXFIT_DATA) ! ep index nearest peak

c R4BNAND_  for filter-dependent quantities
c R4SN_     for SN-dependent quantities (scalars)

      REAL*8  R8EP_MJD(MXFIT_DATA)

      REAL*4
     &    R4BAND_TREST_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_XTMW_NEARPEAK(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_FIT(MXFILT_ALL)
     &   ,R4BAND_SNRMAX_RAW(MXFILT_ALL)
c
     &   ,R4SN_TEARLY, R4SN_TLATE
     &   ,R4SN_MJDmin, R4SN_MJDmax
     &   ,R4SN_FFSUM_DATA     !  sum F_data**2/sigma^2
     &   ,R4SN_FFSUM_MODEL    !  sum F_model**2/sigma^2
     &   ,R4SN_FFSUM_CROSS    !  sum F_data*F_model/sigma^2
     &   ,R4SN_FFSUM_WGT
     &   ,R4SN_FFSUM_RATIO
     &   ,RADIUS_POP   ! e.g., sqrt [  (x1/3)^2 + (c/0.3)^2 ]

c define covariance matrices for SN model correlations (NOT for fit)

      REAL*8
     &   COVMAT1(MXFIT_DATA*MXFIT_DATA)  ! 1-dim matrix from get_covar
     &  ,COVMAT2(MXFIT_DATA,MXFIT_DATA)  ! 2-dim matrix to invert
     &  ,COVMAT_MIN    ! min value among all elements
     &  ,COVMAT_MAX    ! max value ...

      CHARACTER
     &   FITMODEL_PATH*(MXCHAR_PATH)          ! path for model params
     &  ,FITMODEL_LIST(MXMODEL_INDEX)*40         ! generic name(s) for each model
     &  ,FITMODEL_VERSION*(MXCHAR_MODELNAME)  ! = FITMODEL_NAME
     &  ,FILTLIST_MODEL*(MXFILT_REST*2)  ! filter string for rest-frame model

c common block

      COMMON / SNFITVAR / FITMODEL_INDEX, NSHAPEPAR
     &  ,FITMODEL_PATH, FITMODEL_LIST, FITMODEL_VERSION
     &  ,LOBS_FITMODEL, LREST_FITMODEL, LSED_FITMODEL
     &  ,DOFIT_PHOTOZ_MCMC_ADJUST
     &  ,NFITDOF, XNFITDOF, NFILT_FIT, ISTORE_ZPULL
     &  ,RESTLAMBDA_MODEL, RESTLAMBDA_USEFIT
     &  ,NFILT_MODEL, FILTLIST_MODEL
     &  ,IFILTMAP_MODEL, IFILTINVMAP_MODEL
     &  ,FCN_FITCHI2
     &  ,LC_FITCHI2,  LC_FITPROB
     &  ,LC_MARGCHI2, LC_MARGPROB
c
     &  ,NFITDATA_TOTAL, NFITDATA_REJECT, NFITDATA
     &  ,I4BAND_EP_NEARPEAK
     &  ,USE_FITCOV, USE_FILT, IFITDATA_USRFUN
     &  ,R4BAND_TREST_NEARPEAK, R4BAND_XTMW_NEARPEAK
     &  ,R4BAND_SNRMAX_FIT, R4BAND_SNRMAX_RAW
     &  ,R4SN_TEARLY, R4SN_TLATE, R4SN_MJDmin, R4SN_MJDmax
     &  ,R4SN_FFSUM_DATA, R4SN_FFSUM_MODEL, R4SN_FFSUM_CROSS
     &  ,R4SN_FFSUM_WGT, R4SN_FFSUM_RATIO, RADIUS_POP
c
     &  ,PEAKMAG_OBS_MODEL,   PEAKMAG_OBS_MODEL_ERR
     &  ,PEAKMAG_REST_MODEL,  PEAKMAG_REST_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL,  PEAKFLUX_OBS_MODEL_ERR
     &  ,PEAKFLUX_OBS_MODEL_COR
     &  ,PEAK_KCOR_MODEL
     &  ,LBKSNINFO, USESIM_FITPAR, REDSHIFT_FIT
     &  ,CUTWIN_FITPAR, CUTWIN_FITCOV, CUTWIN_FITERRz1
     &  ,USE_LANDOLT_REST, USE_LANDOLT_OBS

      COMMON / COVMAT8 /
     &   COVMAT1, COVMAT2, COVMAT_MIN, COVMAT_MAX

      COMMON / SNFITVAR8 / R8EP_MJD

c define photoZ variables for photoZ fit.

      REAL
     &   PHOTOZ_ERR_SNFIT    ! photoZ error from SN photoz fit
     &  ,PHOTOZ_ERR_SNHOST   ! photoZ error from host gal
     &  ,PHOTOZ_ERR_SNMAG    ! photoZ error from intrinsic SN mag error
     &  ,PHOTOZ_ERR_ZPULL    ! photoZdif(SN-host) / error
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR ! actual z prior used in fit
c
     &  ,PHOTOZ_DROPFILTER_MIN(MXFILT_ALL)  ! min valid Z
     &  ,PHOTOZ_DROPFILTER_MAX(MXFILT_ALL)  ! max valid Z
     &  ,PHOTODZ_MIN(MXITER)    ! min | PHOTOZ-Zvalid(model) |
     &  ,PHOTODZ1Z_MIN(MXITER)  ! idem ind dZ/(1+z) space
c
     &  ,PHOTOZ_RANGE_KCOR(2)
c
c ? DOFIT_PHOTOZ_HOST=> DOFIT_PHOTOZ_GAUSS

      LOGICAL
     &   DOFIT_PHOTOZ_HOST      ! T=> include host-photoz
     &  ,DOFIT_PHOTOZ_noHOST    ! T=> no host-photoz
     &  ,DOFIT_PHOTOZ_CHEAT     ! T=> cheater option
     &  ,PHOTOZ_DROPFILTER(MXFILT_ALL)  ! T=> filter was dropped
     &  ,PHOTOZ_ADDFILTER(MXFILT_ALL)   ! T=> filter added

      INTEGER MASK_PHOTOZ_SOURCE  ! set used OPT_PHOTOZ bits

      INTEGER IFILT_NEARDROP  ! used filt-index nearest to gettinng dropped

      COMMON / PHOTOZCOM / MASK_PHOTOZ_SOURCE
     &  ,DOFIT_PHOTOZ_HOST, DOFIT_PHOTOZ_noHOST, DOFIT_PHOTOZ_CHEAT
     &  ,PHOTOZ_ERR_SNFIT, PHOTOZ_ERR_SNHOST, PHOTOZ_ERR_SNMAG
     &  ,PHOTOZ_ERR_ZPULL
     &  ,PRIOR_PHOTOZ, PRIOR_PHOTOZ_ERR  ! Feb 2022
     &  ,PHOTOZ_DROPFILTER_MIN, PHOTOZ_DROPFILTER_MAX
     &  ,PHOTOZ_DROPFILTER, PHOTOZ_ADDFILTER
     &  ,PHOTODZ_MIN, PHOTODZ1Z_MIN, IFILT_NEARDROP
     &  ,PHOTOZ_RANGE_KCOR

c define variables for prior on each fit variable.
c CHI2GRID_PRIOR is a grid storing chi2-values to add.

      INTEGER NBIN_PRIOR
      PARAMETER ( NBIN_PRIOR = 1000 )

      REAL*8
     &   PRIOR_CHI2GRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_PROBGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_VALGRID(NBIN_PRIOR,IPAR_MAX)
     &  ,PRIOR_RANGE(2,IPAR_MAX)
     &  ,PRIOR_BINSIZE(IPAR_MAX)
     &  ,FLATPRIOR_RANGE(2,IPAR_MAX)  ! used to interp near discontinuity

      LOGICAL USE_PRIOR(IPAR_MAX), USE_PRIOR_AV

      INTEGER FLATPRIOR_BINRANGE(2,IPAR_MAX)

      COMMON / PRIORCOM8 /
     &    PRIOR_CHI2GRID, PRIOR_PROBGRID, PRIOR_VALGRID
     &  , PRIOR_RANGE, PRIOR_BINSIZE
     &  , FLATPRIOR_RANGE, FLATPRIOR_BINRANGE

      COMMON / PRIORCOM4 / USE_PRIOR, USE_PRIOR_AV



C +CDE,SNFITINP. inserted below by ypatchy. 

c namelist input variables.

      CHARACTER
     &    FITMODEL_NAME*(MXCHAR_FILENAME)    ! I: path/model
     &   ,FITCOVAR_FILE*(MXCHAR_FILENAME)    ! I: '' => default, 'SIM' => from sim
     &   ,SIMEFF_FILE*(MXCHAR_FILENAME)      ! sim-eff file for PRIOR
     &   ,STRETCH_TEMPLATE_FILE*(MXCHAR_FILENAME)  ! template for stretch model
     &   ,SALT2_DICTFILE*(MXCHAR_FILENAME)    ! output for SALT2's HUBBLEFIT
     &   ,FILTLIST_FIT*(MXFILT_ALL)    ! I: char list of filters to fit:
     &                            ! I: examples: 'gri' or 'g r i', etc ...
     &   ,FILTLIST_DMPFCN*20      ! I: idem for CHI2FUN [FCN] dump
     &   ,FILTLIST_DMPFUN*20      ! I: idem for USRFUN [flux-fun] dump
     &   ,NEARFILT_IGNORE_REST*20 ! I: ignore these nearest rest-filters
     &   ,FILTLAM_SHIFT*100       ! I: 'U 42.  B 22. etc ...'
     &   ,FILTER_FITMAGDIF*4      ! I: fit magObs in this filter 2 ways for test

      CHARACTER
     &   FILTLIST_FITRESTMAG*12     ! I: fit for these restMag filters
      REAL
     &   LUMIFIX_FITRESTMAG       ! I: fix shape par to this value (legacy name)
     &  ,SHAPEFIX_FITRESTMAG      ! I: same as above
     &  ,COLORFIX_FITRESTMAG      ! I: fix color par to this value
     &  ,LAMEXTRAP_FITRESTMAG     ! I: allow this much rest-frame extrapolation
     &  ,DLAMTOL_FITRESTMAG       ! I: allow this lam-tolerance for closest bands

      LOGICAL
     &    DOFIT_FILT(0:MXFILT_ALL)
     &   ,LDMPFCN(0:MXFILT_ALL)
     &   ,LDMPFUN(MXFILT_ALL)
     &   ,LDMPFCN_PLOTCHI2(MXFILT_ALL)
     &   ,LDMPFUN_PLOTCHI2(MXFILT_ALL)
     &   ,LFIXPAR_ALL       ! I: T=> fix all paramters; FITVAL = INIVAL
     &   ,LFIXPAR_ADJUST    ! I: T=> leave params based on FITINI_ADJUST
     &   ,LKCOR_STRETCH     ! I: T=> get Kcor from stretched template
     &   ,LKCOR_AVWARP      ! I: T=> get Kcor from color-warped template
     &   ,USE_MODEL_MAGERR  ! I: T=> use mag error from model
     &   ,ENABLE_MAGSHIFT_SALT2  ! I: T=> enable mag shifts from training
     &   ,ENABLE_WAVESHIFT_SALT2 ! I: T=> enable wave shifts from training
     &   ,ALLOW_NEGFLUX_SALT2    ! I: T=> alow Flam < 0; otherwise force Flam=0
     &   ,ADD_SALT2ERR_FROMz     ! I: T=> add SALT2 param errors from zerr
     &   ,USESIM_COLOR      ! I: T=> use simulated color (AV,c ...)
     &   ,USESIM_AV         ! I: T => use sim. AV in fit (only if LSIM=T)
     &   ,USESIM_RV         ! I: T => idem for RV
     &   ,USESIM_LUMIPAR    ! I: T => use sim lumipar in fit (legacy name)
     &   ,USESIM_SHAPE      ! I: T => use sim shape value in fit
     &   ,USESIM_PEAKMJD    ! I: T => use sim peakMJD
     &   ,USESIM_DLMAG      ! I: T => use sim DLMAG
     &   ,USESIM_REDSHIFT   ! I: T => use sim redshift in fit
     &   ,USESIM_INIVAL     ! I: T => use sim params as initial values
     &   ,MINOS_ERR_DLMAG   ! I: T=> require valid MINOS error for DLMAG
     &   ,MINOS_ERR_REQALL0 ! I: T=> require all MINOS errors to be valid
     &   ,MINOS_ERR_REQALL1 ! I: T=> require all but 1 MINOS errors to be valid
     &   ,MINOS_ERRMAX_BAD  ! I: T=> flag too-small errors (def=T)
     &   ,UCOR_BXB          ! I: T=> correct U-band with BX-B
     &   ,LTRACE            ! I: T=> debug tool to identify crashes
     &   ,LPLOTCHI2         ! I: T=> plot chi2 vs. each fitpar & filter
     &   ,DOCHI2_SIGMA      ! I: T=> add chi2 from model-error
     &   ,CHECK_CRAZYFITERR ! I: T=> check for crazy fit errors (default)

c option to compute Zmax/Vmax for 1/Vmax method (Jun 2013)
      CHARACTER MAGLIM_VMAX*60   ! I: e.g., 'r 21.5  i 22.0'
      INTEGER   OPT_VMAX         ! I: integer mask of options

c Note that _REJECT refer to epochs after 1st fit iteration ;
c these epochs are rejected before 2nd fit.
c FITWIN_XXX refer to cuts on final fit parameters, and are apply to SN.
c Jun 2015: FITWIN_AV -> FITWIN_COLOR

      REAL
     &   RESTLAMBDA_FITRANGE(2)  ! I: rest-frame central lambda range (A)
     &  ,UVLAM_EXTRAPFLUX      ! I: extrapolate SED model back to this lambda
     &  ,DELCHI2_REJECT        ! I: reject epoch at 2nd iter if chi2 >
     &  ,SIGNOISE_REJECT       ! I: reject epoch below this signal/noise
     &  ,TREST_REJECT(2)       ! I: reject epoch at 2nd iter if fails Trest
     &  ,MJD_REJECT(2)         ! I: reject epoch at 2nd iter that fail MJD cut
     &  ,PEAKMJD_SANITY(2)     ! I: sanity check window on fit PEAKMJD
     &  ,FITWIN_ZPULL(2)       ! I: cut-window for ZPULL
     &  ,FITWIN_ZPHOT(2)       ! I: cut-windo on photoz (Dec 2014)
     &  ,FITWIN_COLOR(2)       ! I: cut-window for COLOR/AV
     &  ,FITWIN_SHAPE(2)       ! I: "         for SHAPE
     &  ,FITWIN_PROB(2)        ! I: cut-window for chi2 prob
     &  ,FITWIN_NOMARG_PROB(2) ! I: cut-window before marginalization
     &  ,FITWIN_CHI2SIGMA(2)   ! I: cut on chi2-contribution from sigma-term
     &  ,FITWIN_TREST(2)       ! I: cut on T - T0 (to replace TREST_REJECT)
     &  ,FITWIN_MJD(2)         ! I: cut on absolute MJD range.
c
     &  ,FITWIN_COV_OFFDIAG(2) ! I: global cut on offDiag fitted cov (9/2016)
     &  ,FITWIN_PEAKMJD_ERR(2) ! I: cut on PEAKMJDerr (9/2016)
     &  ,FITWIN_MB_ERR(2)      ! I: cut on mBerr  (9/2016)
     &  ,FITWIN_SHAPE_ERR(2)   ! I: cut on x1err or delta_err (9/2016)
     &  ,FITWIN_COLOR_ERR(2)   ! I: cut on cerr or AVerr (9/2016)
c
     &  ,FITWIN_PEAKMJD_ERRz1(2)! I: cut on PEAKMJDerr/(1+z), added Mar 2017
     &  ,FITWIN_MB_ERRz1(2)     ! I: cut on NBerr/(1+z)
     &  ,FITWIN_SHAPE_ERRz1(2)  ! I: cut on x1err/(1+z)
     &  ,FITWIN_COLOR_ERRz1(2)  ! I: cut on cerr/(1+z)
c
     &  ,INISTP_PEAKMJD       ! I: initial step size for MJD  (days)
     &  ,INISTP_AV            ! I: initial step size for AV
     &  ,INISTP_RV
     &  ,INISTP_AVRV          ! I: non-zero => fit for AV/RV instead of RV
     &  ,INISTP_COLOR         ! I: initiaql step for color param
     &  ,INISTP_DLMAG         ! I: initial step for lumi-distance mu
     &  ,INISTP_X0            ! I: initial step for SALT2 x0
     &  ,INISTP_PHOTOZ        ! I: initial step for photo-redshift
     &  ,INISTP_SHAPE         ! I: initial step for shape-par
     &  ,INISTP_SHAPE2        ! I: initial step for 2nd shape-par
c
     &  ,INIVAL_PEAKMJD       ! I: initial value for MJD  (days)
     &  ,INIVAL_PEAKMJD_SHIFT ! I: shift INIVAL_PEAKMJD by this much
     &  ,INIVAL_RV            ! I: initial value for RV
     &  ,INIVAL_AV            ! I: initial value for AV
     &  ,INIVAL_AVRV          ! I:
     &  ,INIVAL_COLOR         ! I: initial value for color
     &  ,INIVAL_DLMAG         ! I: initial value lumi-distance m
     &  ,INIVAL_X0            ! I: initial value for x0
     &  ,INIVAL_PHOTOZ        ! I: initial value photo-redshift
     &  ,INIVAL_SHAPE         ! I: initial value shape-par
     &  ,INIVAL_SHAPE2        ! I: idem for 2nd shape-par
     &  ,INIVAL_SHIFT_ERRFRAC ! I: after 1st iter, INIVAL += FITERR*ERRFRAC
     &  ,FRACERRDIF_REPEATFIT ! I: repeat fit with MINOS if FRACERRDIF > thius
c
     &  ,INIVAL_GRIDSEARCH_DPEAKMJD(3)  ! I: min,max w.r.t. t0_approx, binsize
     &  ,INIVAL_GRIDSEARCH_COLOR(3)     ! I: min,max,binsize
c
     &  ,PRIOR_AVEXP(2)   ! I: 2 exp slopes for AV prior
     &  ,PRIOR_AVWGT(2)   ! I: 2 exp wgts for AV prior
     &  ,PRIOR_AVRES      ! I: gaussian smearing on exponential prior
     &  ,PRIOR_MJDSIG     ! I: add chi2 = [(MJD - MJDINI)/MJDSIG]^2
     &  ,PRIOR_SHAPE_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_SHAPE_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_SHAPE2_RANGE(2) ! I: min,max for FLAT SHAPE2 prior
     &  ,PRIOR_SHAPE2_SIGMA    ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_COLOR_RANGE(2)  ! I: min,max for FLAT SHAPE prior
     &  ,PRIOR_COLOR_SIGMA     ! I: sigma for guassian roll-off on FLAT prior
     &  ,PRIOR_LUMIPAR_RANGE(2)  ! I: idem, legacy variable
     &  ,PRIOR_LUMIPAR_SIGMA     ! I: idem, legacy variable
     &  ,PRIOR_DELTA_PROFILE(4)  ! I: DELTA-prior pars: sig(low,up) & min
c
     &  ,FUDGE_COVAR      ! I: fudge normalized covariances (0=> no fudge)
     &  ,SCALE_COVAR      ! I: scale entire covariance matrix by this factor
     &  ,LANDOLT_COLOR_SHIFT(10)  ! shifts in color terms (if OPT_LANDOLT>0)
     &  ,ZSCALE_SIMEFF         ! scale redshift for SIMEFF call.
     &  ,TREST_PEAKRENORM(2)   ! I: Trest-range to renorm peakFlux for FPKRAT
     &  ,TREST_DMPFUN(2)       ! I: Trest-range for FILTLIST_DMPFUN
     &  ,SCALE_PLOTCHI2        ! I: for HFUNMIN
     &  ,SALT2alpha            ! I: needed for constrained photoZ fit
     &  ,SALT2beta             ! I: idem
     &  ,LAMREST_MODEL_SMOOTH  ! I: smooth rest-model at filter-jump

      INTEGER
     &   OPT_NEARFILT      ! I: 4=> 2nd closest filter from MLCS2k2
     &  ,OPT_COVAR         ! I: legacy name for OPT_COVAR_FLUX
     &  ,OPT_COVAR_FLUX    ! I: options for using flux-covariance matrix
     &  ,OPT_COVAR_MWXTERR ! I: 1 => use MW error in cov matrix
     &  ,OPT_XTMW_ERR      ! I: legacy variable: set to OPT_COVAR_MWXTERR
     &  ,OPT_COVAR_LCFIT   ! I: option to fix non-invertible COV(mB,x1,c)
     &  ,OPT_SNXT          ! I: SN extinction options (depends on model)
     &  ,OPT_KCORERR       ! I: Kcor error option (2=>SJ)
     &  ,OPT_LANDOLT       ! I: bit1 => convert Bessell -> Landolt
     &  ,OPT_PRIOR         ! I: 1=use prior; 0=turn off all priors
     &  ,OPT_PRIOR_AV      ! I: 1=> nominal (default), 0=> flat
     &  ,OPT_PRIOR_SIMEFF  ! I: internally set based on SIMEFF_FILE
     &  ,OPT_SIMEFF        ! I: obsolete => ABORT if non-zero !!!
     &  ,OPT_MNSTAT_COV    ! I: 1-> repeat on bad value
     &  ,SIMFIT_IDEAL_PRESCALE  ! I: pre-scale sample for including IDEAL fit
     &  ,NGRID_PDF     ! I: number of grid-bins for each dimens of pdf
     &  ,NSIGMA_PDF    ! I: compute PDF for +- NSIGMA_PDF
     &  ,MAX_INTEGPDF  ! I: max # times to integrate PDFs
     &  ,CONTOUR_LIST(4,20)  ! I: define contour plots: CID,IPAR1,IPAR2,NPT
     &  ,OPT_SALT2FIT  ! I: fit 0=> fit x0;  1=> fit log10(x0); 2=> fit delta-mu
     &  ,IPAR_PLOTCHI2 ! I: HFUNMIN only for this parameter
     &  ,NFIT_VERBOSE  ! I: number of verbose printouts (avoid huge logs)

C ----------------------
c define all of the PHOTOZ options here in one place
c (except for INISTP_PHOTOZ ande INIVAL_PHOTOZ)

      LOGICAL
     &   DOFIT_PHOTOZ       ! I: T=> fit SN photo-redshift
     &  ,SKIP_PHOTOZ_INIT   ! I: T=> skip initial parameter estimate
     &  ,LDMP_PHOTOZ_DROPFILTER  ! I: T=> dump reason for dropped filter

      INTEGER
     &   OPT_PHOTOZ  ! I: bit 0 (1 ) => use host-galaxy ZPRIOR;
                     ! I: bit 1 (2 ) => use spectro Z-prior
                     ! I: bit 2 (4 ) => use zPhot quantiles
                     ! I: bit 4 (16) => cheat: start with Zspec and correct filt
     &  ,ISCALE_COURSEBIN_PHOTOZ  ! I: scale number of course-grid bins for init
     &  ,NEVAL_MCMC_PHOTOZ

      REAL
     &   PHOTOZ_ITER1_LAMRANGE(2)  ! I: cut on obs-filter, ITER=1 only
     &  ,PHOTOZ_BOUND(2)       ! I: MINUIT bound for photoz fit
     &  ,PHOTODZ_REJECT        ! I: reject filters in photoZ fit (see code)
     &  ,PHOTODZ1Z_REJECT      ! I: idem for dz/(1+z)
     &  ,PRIOR_ZERRSCALE       ! I: scale hostZ-error for z-prior in photoZ fits
     &  ,PRIOR_MUERRSCALE      ! I: scale MU-error for x0-prior in photoZ fits
     &  ,SNMAGRMS_for_PHOTOZ   ! I: compute PHOTOZ error from SNMAGRMS
     &  ,PARLIST_MCMC_PHOTOZ(5) ! params for MCMC burn-in

c define varibales to fudge the data errors for particular
c TREST-range and passbands. Note that FUDGE_MAGERR_MODEL
c globally replaces the model error, while FUDGE_FITERR_MAXFRAC
c is added to chi2-error in the specified passbands and Trest range.

      INTEGER
     &   FUDGE_FITERR_MAXITER     ! I: see manual

      REAL
     &   FUDGE_FITERR_MAXFRAC      ! I: add fit-error = this fraction of maxflux
     &  ,FUDGE_FITERR_TREST(4)     ! I: apply err-fudge to two TREST-ranges
     &  ,FUDGE_FITERR_RESTLAM(4)   ! I: "      "        to RESTLAM range
     &  ,FUDGE_MAGERR_MODEL        ! I: fix model mag-error
     &  ,FUDGEALL_MAXFRAC          ! I: MAXFRAC fudge for all epochs
     &  ,FUDGEALL_ITER1_MAXFRAC    ! I: idem, but 1st iteration only
     &  ,FUDGE_DATAERR_SCALE       ! I: re-scale all data  errors.
     &  ,FUDGE_MODELERR_SCALE      ! I: re-scale all model errors.

      CHARACTER
     &   FUDGE_FITERR_PASSBANDS*(MXFILT_ALL) ! I: apply err-fudge to these bands

c allow TREST-cut to depend on filter (to override global FITWIN_TREST cut)
      CHARACTER
     &  FITWIN_TREST_FILTER*120    ! I: e.g., 'gr -10.0 50.0  iz 0 50'
      REAL
     &  FITWIN_TREST_FILT(2,MXFILT_ALL)  ! Trest window for each filter

      LOGICAL
     &   DOFUDGE_FITERR(MXFILT_ALL) ! internal logical computed from above
     &  ,USE_FUDGE_FITERR           ! internal logical
     &  ,DOPRIOR_DLMAG              ! internal logical


      COMMON / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_FILT, DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LDMPFCN, LDMPFUN, LDMPFCN_PLOTCHI2, LDMPFUN_PLOTCHI2
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE,   PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE,   PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE,  PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_PRIOR_SIMEFF, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS, DOFUDGE_FITERR, USE_FUDGE_FITERR
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL, FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta, OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

c ------

      NAMELIST / FITINP /
     &    FITMODEL_NAME, RESTLAMBDA_FITRANGE, UVLAM_EXTRAPFLUX
     &   ,FILTLIST_FIT
     &   ,FILTLIST_DMPFCN, FILTER_FITMAGDIF
     &   ,FILTLIST_FITRESTMAG, LUMIFIX_FITRESTMAG, SHAPEFIX_FITRESTMAG
     &   ,COLORFIX_FITRESTMAG, LAMEXTRAP_FITRESTMAG, DLAMTOL_FITRESTMAG
     &   ,FILTLIST_DMPFUN, TREST_DMPFUN, SCALE_PLOTCHI2
     &   ,NEARFILT_IGNORE_REST, FILTLAM_SHIFT
     &   ,DOFIT_PHOTOZ, SKIP_PHOTOZ_INIT
     &   ,LDMP_PHOTOZ_DROPFILTER
     &   ,LFIXPAR_ALL, LFIXPAR_ADJUST, LKCOR_AVWARP, LKCOR_STRETCH
     &   ,USE_MODEL_MAGERR, DOCHI2_SIGMA, LAMREST_MODEL_SMOOTH
     &   ,CHECK_CRAZYFITERR, SIMEFF_FILE, ADD_SALT2ERR_FROMz
     &   ,ENABLE_MAGSHIFT_SALT2, ENABLE_WAVESHIFT_SALT2
     &   ,ALLOW_NEGFLUX_SALT2
     &   ,STRETCH_TEMPLATE_FILE, SALT2_DICTFILE
     &   ,DELCHI2_REJECT, SIGNOISE_REJECT, PEAKMJD_SANITY
     &   ,FITWIN_ZPULL, FITWIN_ZPHOT
     &   ,FITWIN_COLOR, FITWIN_SHAPE, FITWIN_MJD
     &   ,FITWIN_PROB, FITWIN_NOMARG_PROB, FITWIN_CHI2SIGMA
     &   ,FITWIN_TREST, FITWIN_TREST_FILTER, FITWIN_TREST_FILT
     &   ,FITWIN_COV_OFFDIAG, FITWIN_PEAKMJD_ERR
     &   ,FITWIN_MB_ERR, FITWIN_SHAPE_ERR, FITWIN_COLOR_ERR
     &   ,FITWIN_PEAKMJD_ERRz1
     &   ,FITWIN_MB_ERRz1, FITWIN_SHAPE_ERRz1, FITWIN_COLOR_ERRz1
     &   ,SNMAGRMS_for_PHOTOZ
     &   ,TREST_REJECT, MJD_REJECT
     &   ,USESIM_AV, USESIM_RV, USESIM_COLOR
     &   ,USESIM_LUMIPAR, USESIM_SHAPE
     &   ,USESIM_PEAKMJD, USESIM_DLMAG, USESIM_REDSHIFT, USESIM_INIVAL
     &   ,INISTP_PEAKMJD, INISTP_AV, INISTP_RV, INISTP_AVRV
     &   ,INISTP_DLMAG, INISTP_X0, INISTP_PHOTOZ, INISTP_COLOR
     &   ,INISTP_SHAPE, INISTP_SHAPE2
     &   ,INIVAL_PEAKMJD, INIVAL_PEAKMJD_SHIFT
     &   ,INIVAL_AV, INIVAL_RV, INIVAL_AVRV
     &   ,INIVAL_DLMAG, INIVAL_PHOTOZ, INIVAL_COLOR, INIVAL_X0
     &   ,INIVAL_SHAPE, INIVAL_SHAPE2, INIVAL_SHIFT_ERRFRAC
     &   ,INIVAL_GRIDSEARCH_DPEAKMJD, INIVAL_GRIDSEARCH_COLOR
     &   ,FRACERRDIF_REPEATFIT
     &   ,OPT_COVAR, OPT_COVAR_FLUX, OPT_COVAR_MWXTERR, OPT_XTMW_ERR
     &   ,OPT_COVAR_LCFIT, OPT_SNXT, OPT_KCORERR, OPT_NEARFILT
     &   ,OPT_LANDOLT, ZSCALE_SIMEFF, UCOR_BXB
     &   ,OPT_PHOTOZ, ISCALE_COURSEBIN_PHOTOZ
     &   ,NEVAL_MCMC_PHOTOZ, PARLIST_MCMC_PHOTOZ
     &   ,FUDGE_COVAR, SCALE_COVAR, LANDOLT_COLOR_SHIFT
     &   ,NGRID_PDF, NSIGMA_PDF, MAX_INTEGPDF
     &   ,PRIOR_AVEXP, PRIOR_AVWGT, PRIOR_AVRES, PRIOR_MJDSIG
     &   ,PRIOR_ZERRSCALE, PRIOR_MUERRSCALE, DOPRIOR_DLMAG
     &   ,PRIOR_COLOR_RANGE, PRIOR_COLOR_SIGMA
     &   ,PRIOR_SHAPE_RANGE, PRIOR_SHAPE_SIGMA
     &   ,PRIOR_SHAPE2_RANGE, PRIOR_SHAPE2_SIGMA
     &   ,PRIOR_LUMIPAR_RANGE, PRIOR_LUMIPAR_SIGMA  ! legacy
     &   ,PRIOR_DELTA_PROFILE
     &   ,OPT_PRIOR, OPT_PRIOR_AV, OPT_SIMEFF
     &   ,OPT_MNSTAT_COV, SIMFIT_IDEAL_PRESCALE
     &   ,MINOS_ERR_DLMAG, MINOS_ERR_REQALL0, MINOS_ERR_REQALL1
     &   ,MINOS_ERRMAX_BAD
     &   ,CONTOUR_LIST, LTRACE, LPLOTCHI2, IPAR_PLOTCHI2, NFIT_VERBOSE
     &   ,FUDGE_FITERR_MAXFRAC, FUDGE_FITERR_TREST
     &   ,FUDGE_FITERR_PASSBANDS
     &   ,FUDGE_FITERR_RESTLAM, FUDGE_MAGERR_MODEL,FUDGE_FITERR_MAXITER
     &   ,FUDGEALL_MAXFRAC, FUDGEALL_ITER1_MAXFRAC
     &   ,FUDGE_DATAERR_SCALE, FUDGE_MODELERR_SCALE
     &   ,FITCOVAR_FILE
     &   ,TREST_PEAKRENORM
     &   ,SALT2alpha, SALT2beta , OPT_SALT2FIT
     &   ,PHOTODZ_REJECT, PHOTODZ1Z_REJECT
     &   ,PHOTOZ_ITER1_LAMRANGE, PHOTOZ_BOUND
     &   ,MAGLIM_VMAX, OPT_VMAX

      EQUIVALENCE ( FITWIN_MJD(1),   MJD_REJECT(1)   )
      EQUIVALENCE ( FITWIN_TREST(1), TREST_REJECT(1) )





C +CDE,SNLCINP. inserted below by ypatchy. 

c define general input to program:
c SN flux version, hbook files, cut-windows, etc ...
c Dec 30 2012: add KCOR_FILE for fits-formatted tables (same name as in sim)
c
      CHARACTER*(MXCHAR_FILENAME)  ! user input files
     &   NMLFILE          ! name of input namelist file
     &  ,HFILE_OUT        ! I: output hbook filename for tables
     &  ,ROOTFILE_OUT     ! I: output filename for root for tables
     &  ,TEXTFILE_PREFIX  ! I: prefix for text file tables
     &  ,MARZFILE_OUT     ! I: output FITS file for input to MARZ (spectra)
     &  ,SNTABLE_LIST     ! I: list of SNTABLEs to create; e.g., 'SNANA FITRES'
     &  ,SNTABLE_APPEND_VARNAME  ! I: add this varname to output tables
     &  ,SNTABLE_FILTER_REMAP ! I: remap filters in tables
     &  ,KCOR_FILE            ! I: fits-formatted KCOR/calib tables
     &  ,OVERRIDE_RESTLAM_BOUNDARY*80 ! I: for kcors; e.g., '5100(gV) 6200(rV)'
     &  ,EPOCH_IGNORE_FILE    ! I: user file with epochs to ignore
     &  ,OUT_EPOCH_IGNORE_FILE ! I: write this file with discarded epochs
     &  ,SNMJD_LIST_FILE      ! I: list of "CID MJD" to process
     &  ,SNMJD_OUT_FILE       ! I: MJD_LIST out file
     &  ,MNFIT_PKMJD_LOGFILE  ! I: separate log for PKMJD fits
     &  ,USERTAGS_FILE        ! I: optional int user tag per SN
     &  ,VPEC_FILE            ! obsolete? pec. velocity corrections
     &  ,SNCID_LIST_FILE      ! I: list of CID's to process
     &  ,SIMLIB_OUT           ! legacy name
     &  ,SIMLIB_OUTFILE       ! I: write simlib entry for each event
     &  ,SIMLIB_ZPERR_LIST    ! I: e.g., 'abc .01 def .02 ghi .005'
     &  ,NONLINEARITY_FILE    ! I: non-linearity map
c
     &  ,FUDGE_HOSTNOISE_FILE  ! legacy: inflate error vs. hostSB (Mar 2015)
     &  ,FLUXERRMODEL_FILE     ! I: DATA ONLY: err-fudge maps
     &  ,SIM_FLUXERRMODEL_FILE ! I: idem, SIM only
     &  ,MAGCOR_FILE           ! I: DATA ONLY: mag-cor for each CID-MJD-band
     &  ,SIM_MAGCOR_FILE       ! I: idem, SIM only

      CHARACTER*(MXFILE_LIST*MXCHAR_FILENAME)
     &    HEADER_OVERRIDE_FILE       ! I: comma-sep list of files with CID VAR
     &   ,SIM_HEADER_OVERRIDE_FILE  ! I: same, but for sims

      CHARACTER  ! versions
     &   VERSION_PHOTOMETRY(MXVERS)*(MXCHAR_VERSION)   ! I: SN versions to read
     &  ,VERSION_PHOTOMETRY_WILDCARD*(MXCHAR_FILENAME) ! I: get list from glob
     &  ,VERSION_REFORMAT_FITS*(MXCHAR_VERSION)   ! I: reformat TEXT -> FITS
     &  ,VERSION_REFORMAT_TEXT*(MXCHAR_VERSION)   ! I: reformat FITS -> TEXT

      CHARACTER ! paths
     &   PRIVATE_DATA_PATH*(MXCHAR_PATH)    ! I: private data subdir
     &  ,FILTER_UPDATE_PATH*(MXCHAR_PATH)   ! I: SN-dependent filter response

      CHARACTER  ! misc
     &   REFORMAT_KEYS*(MXCHAR_FILENAME)  !   global reformat info
     &  ,NONSURVEY_FILTERS*(MXFILT_ALL)   ! I: non-survey filters to add
     &  ,SNRMAX_FILTERS*(MXFILT_ALL)      ! I: list of filters for SNRMAX cuts
     &  ,FILTER_REPLACE*(MXFILT_ALL)      ! I: e.g., 'UGRIZ -> ugriz'
     &  ,FILTLIST_LAMSHIFT*(MXFILT_ALL)   ! I: list of lam-shifted filters
     &  ,PRIVATE_CUTWIN_STRING(MXCUT_PRIVATE)*(MXCHAR_CUTNAME) ! I: cut on privat variables
     &  ,PRIVATE_VARNAME_READLIST*200   ! I: list of private vars to read (default=ALL)
     &  ,SIMVAR_CUTWIN_STRING*(MXCHAR_CUTNAME) ! I: cuts on SIM_XXX
     &  ,EARLYLC_STRING*(MXCHAR_CUTNAME)       ! I: see manual
     &  ,REQUIRE_EPOCHS_STRING*100  ! I: e.g., 'riz 10 7 20' uses CUTWIN_SNRMAX
     &  ,DUMP_STRING*100            ! 'funName CID-list'

      INTEGER
     &   NFIT_ITERATION       ! I: number of fit iterations
     &  ,MINUIT_PRINT_LEVEL   ! -1 -> none
     &  ,INTERP_OPT           ! I:  interp option (see INTERP_XXX params)
     &  ,NLINE_ARGS
     &  ,OPT_YAML             ! I: 1=> write YAML out even if not batch job
     &  ,OPT_REFORMAT_TEXT    ! I: 1=> re-write SNDATA files in text format; see manual options
     &  ,OPT_REFORMAT_FITS    ! I: 1=> re-write in FITSformat (data only); see manual options
     &  ,OPT_REFORMAT_SALT2   ! I: 1=> re-write SNDATA files in SALT2 format
     &  ,OPT_REFORMAT_SPECTRA ! I: 1=> 3-col text: lam, Flam, Flamerr (ignore photometry)
     &  ,OPTSIM_LCWIDTH       ! I: 1=> option to compute LC width
     &  ,DEBUG_FLAG           ! I: for internal debug
     &  ,JOBSPLIT(2)          ! I: for batch; process (1)-range of (2)=TOTAL
     &  ,JOBSPLIT_EXTERNAL(2) ! passed by submit_batch for text format
     &  ,MXLC_FIT             ! I: stop after this many fits passing all cuts
     &  ,PHOTFLAG_DETECT      ! I: used to count NEPOCH_DETECT and TLIVE_DETECT
     &  ,PHOTFLAG_TRIGGER     ! I: determine MJD(trigger) for survey
     &  ,FLUXERRMODEL_OPTMASK ! I: see manual
     &  ,OPT_SIMLIB_OUT       ! I: bit mask of SIMLIB_OUT options
     &  ,SIMLIB_OUT_TMINFIX   ! I: choose PEAKMJD so that min(MJD-PEAKMJD)=TMINFIX
     &  ,REQUIRE_DOCANA
     &  ,OPT_SNCID_LIST      ! I: 1=force all and ignore cuts; 2=use PKMJDINI

      LOGICAL
     &   LSIM_SEARCH_SPEC   ! I: T => require simulated SPEC-tag
     &  ,LSIM_SEARCH_ZHOST  ! I: T => require simulated zHOST
     &  ,LTEST_INTERP       ! I: T => calls TEST_KCOR
     &  ,LTEST_KCOR         ! I: T => calls TEST_INTERP
     &  ,LTEST_MAG          ! I: T => test GET_MAGLC  and GET_MWXT
     &  ,LTEST_U3BAND       ! I: T => require exactly 3 bands that include U
     &  ,USE_LINE_ARGS(MXLINE_ARGS)
     &  ,USE_SNHOST_ZPHOT    ! I: T=> replace SNLC_REDSHIFT -> SNHOST_ZPHOT
     &  ,USE_HOSTGAL_PHOTOZ  ! I: idem, but matches keyName in data files
c
     &  ,ABORT_ON_NOEPOCHS   ! I: T=> abort if there are no epochs to fit
     &  ,ABORT_ON_BADAVWARP  ! I: T=> abort if AVwarp cannot be determined
     &  ,ABORT_ON_BADZ       ! I: T=> abort on bad z in GET_KCOR8
     &  ,ABORT_ON_BADKCOR    ! I: T=> affects only the init stage (RDKCOR)
     &  ,ABORT_ON_BADSURVEY  ! I: T=> abort if SURVEY changes
     &  ,ABORT_ON_BADFILTER  ! I: T=> abort if fit band is not in SURVEY filters
     &  ,ABORT_ON_MARGPDF0   ! I: T=> abort if marginalized pdf=0 everywhere
     &  ,ABORT_ON_TRESTCUT   ! I: T=> abort if any Trest cut is set (for photoz)
     &  ,ABORT_ON_DUPLCID    ! I: T=> abort on duplicate CID
     &  ,ABORT_ON_DUPLMJD    ! I: T=> abort on repeat MJD+band (Jun 2017)
     &  ,ABORT_ON_NOPKMJD    ! I: T=> abort if no PKMJDINI (see OPT_SETPKMJD)
     &  ,USE_MINOS           ! I: T=> use MINOS instead of MINIMIZE
     &  ,LDMP_SNFAIL         ! I: T => dump reason for each SN failure
     &  ,LDMP_SNANA_VERSION  ! I: T => dump SNANA version and SNANA_DIR
     &  ,LDMP_AVWARP         ! I: dump GET_AVWARP8 (debug only)
     &  ,LDMP_KCORFUN        ! I: dump KCORFUN8 (debug only)
     &  ,LDMP_SATURATE       ! I: dump saturated observations
     &  ,USESIM_SNIA         ! I: default True -> process simulated SNIa
     &  ,USESIM_NONIA        ! I: default True -> process simulated nonIa
     &  ,USESIM_TRUEFLUX     ! I: SNLC_FLUXCAL -> SIM_FLUXCAL
     &  ,LPROB_TRUEFLUX      ! I: T=> compute F-Ftrue chi2 and PROB
     &  ,RESTORE_WRONG_VPEC  ! I: restore incorrect VPEC sign correction
     &  ,RESTORE_OVERRIDE_ZBUG ! I: restore z=zCMB insteead of zHEL
     &  ,RESTORE_MWEBV_ERR_BUG ! I: bug used MWEBV/6 if MWEBV_ERR < 0.001
     &  ,USE_KCOR_REFACTOR     ! I: use refactored KCOR C-code
     &  ,USE_KCOR_LEGACY

c LC plot info

      INTEGER
     &  MXLC_PLOT      ! I: max number of plots to make with SNLCPAK
     & ,NCCID_PLOT     ! I: size of SNCCID_PLOT array
      CHARACTER
     &  SNCCID_PLOT(MXLISTNML)*(MXCHAR_CCID) ! I: string-list of CCIDs to plot
      REAL
     &   MJDPERIOD_PLOT  ! I: fold LC onto this period (periodic transients)
     &  ,MJDSHIFT_PLOT   ! I: shift MJD for LC plot output

      REAL
     &   DTOBS_MODEL_PLOT  ! I: binning (days) for overlaid best-fit model
     &  ,zTOL_HELIO2CMB    ! I: give warning if  zCMB and zHEL are off

c Oct 2014: variables to check for multi-season transient activity

      INTEGER
     &   MULTISEASON_OPTMASK      ! option(s) for GET_MULTISEASON
      REAL
     &   MULTISEASON_TGAP              ! new season if time-gap > this
     &  ,MULTISEASON_NREJECT_OUTLIER   ! num outliers to reject per season
     &  ,MULTISEASON_CHI2RED_ACTIVE    ! min chi2red for active season

      REAL
     &   SIM_PRESCALE        ! I: pre-scale applied only to SIM
     &  ,VPEC_ERR_OVERRIDE   ! I: override VPEC_ERR in data header (km/sec)
     &  ,SNTABLE_APPEND_VALUE   ! I: value for SNTABLE_APPEND_VARNAME
     &  ,QUANTILE_ZERRMIN ! I: use quantile prior for zerr> this; else use Guass prior

c variables to control estimate of PEAKMJD
      INTEGER
     &   OPT_SETPKMJD            ! I: bit-mask options  to determined PKMJD
      REAL
     &   SNRCUT_SETPKMJD         ! I: define SNR for Fmax in clump method
     &  ,MJDWIN_SETPKMJD         ! I: MJD window for Fmax in clump method
     &  ,SHIFT_SETPKMJD          ! I: shift initial PKMJD for systematic test

c define reference cosmological parameters (double precision!)
c Aug 7, 2009: each parameter has dimension 2 for value & error

      REAL*8
     &   H0_REF(2)    ! I: reference H0  (70 => 70 km/s/MPc)
     &  ,OLAM_REF(2)  ! I: OMEGA_LAMBDA & uncertainty (for x0 prior)
     &  ,OMAT_REF(2)  ! I: OMEGA_MATTER & uncertainty (for x0 prior)
     &  ,ORAD_REF(2)  ! I: OMEGA_RAD & uncertainty (for x0 prior)
     &  ,W0_REF(2)    ! I: DE eq stat w = p/rho & uncertainty (for x0 prior)
     &  ,DWDA_REF(2)  ! I: DE dw/da [a = 1/(1+z)] & uncertainty

      INTEGER   NSIMVAR_CUTWIN
      REAL      SIMVAR_CUTWIN(2,MXCUT_PRIVATE)
      CHARACTER SIMVAR_CUTWIN_LIST(MXCUT_PRIVATE)*40

      COMMON   / SNLCINP /
     &      NLINE_ARGS, USE_LINE_ARGS, nmlfile
     &    , VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &    , MAGCOR_FILE, SIM_MAGCOR_FILE,  FUDGE_HOSTNOISE_FILE
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_zHOST
     &    , LDMP_AVWARP, LDMP_KCORFUN, LDMP_SNFAIL, LDMP_SNANA_VERSION
     &    , LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &    , EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &    , CUTWIN_LAMREST, CUTWIN_LAMOBS, cutwin_snr_nodetect
     &    , PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &    , SIMVAR_CUTWIN_STRING
     &    , NSIMVAR_CUTWIN, SIMVAR_CUTWIN, SIMVAR_CUTWIN_LIST
     &    , EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
     &    , CUTWIN_ZPADU, CUTWIN_ZPNPE, CUTWIN_TREST_TRUEFLUX

      COMMON / SNLCINP8 /
     &    H0_REF, OLAM_REF, OMAT_REF, ORAD_REF, W0_REF, DWDA_REF

      NAMELIST / SNLCINP /
     &      VERSION_PHOTOMETRY, VERSION_PHOTOMETRY_WILDCARD
     &    , VERSION_REFORMAT_FITS, VERSION_REFORMAT_TEXT
     &    , PRIVATE_DATA_PATH, FILTER_UPDATE_PATH
     &    , NONSURVEY_FILTERS, SNRMAX_FILTERS, VPEC_ERR_OVERRIDE
     &    , FILTER_REPLACE, FILTLIST_LAMSHIFT
     &    , JOBSPLIT, JOBSPLIT_EXTERNAL, SIM_PRESCALE, MXLC_FIT
     &    , OPT_YAML
     &    , OPTSIM_LCWIDTH, OPT_REFORMAT_SPECTRA, OPT_REFORMAT_TEXT
     &    , OPT_REFORMAT_SALT2, REFORMAT_KEYS, OPT_REFORMAT_FITS
     &    , SNMJD_LIST_FILE, SNMJD_OUT_FILE, MNFIT_PKMJD_LOGFILE
     &    , hfile_out, rootfile_out, textfile_prefix
     &    , SNTABLE_LIST, SNTABLE_FILTER_REMAP, MARZFILE_OUT
     &    , SNTABLE_APPEND_VARNAME, SNTABLE_APPEND_VALUE
     &    , KCOR_FILE, OVERRIDE_RESTLAM_BOUNDARY, USERTAGS_FILE
     &    , VPEC_FILE, HEADER_OVERRIDE_FILE, SIM_HEADER_OVERRIDE_FILE
     &    , EPOCH_IGNORE_FILE, OUT_EPOCH_IGNORE_FILE
     &    , SNCID_LIST_FILE, OPT_SNCID_LIST, NONLINEARITY_FILE
     &    , SIMLIB_OUT, SIMLIB_OUTFILE, SIMLIB_ZPERR_LIST
     &    , OPT_SIMLIB_OUT, SIMLIB_OUT_TMINFIX
     &    , NFIT_ITERATION, MINUIT_PRINT_LEVEL, INTERP_OPT, USE_MINOS
     &    , OPT_SETPKMJD, QUANTILE_ZERRMIN
     &    , SNRCUT_SETPKMJD, MJDWIN_SETPKMJD, SHIFT_SETPKMJD, DEBUG_FLAG
     &    , LSIM_SEARCH_SPEC, LSIM_SEARCH_ZHOST
     &    , LDMP_SNFAIL, LDMP_SNANA_VERSION, LDMP_SATURATE
     &    , LTEST_KCOR, LTEST_INTERP, LTEST_MAG, LTEST_U3BAND
     &    , USESIM_SNIA, USESIM_NONIA, USESIM_TRUEFLUX
     &    , USE_SNHOST_ZPHOT, USE_HOSTGAL_PHOTOZ
     &    , RESTORE_WRONG_VPEC, RESTORE_OVERRIDE_ZBUG
     &    , RESTORE_MWEBV_ERR_BUG, USE_KCOR_REFACTOR, USE_KCOR_LEGACY
     &    , REQUIRE_DOCANA
     &    , LPROB_TRUEFLUX
     &    , ABORT_ON_NOEPOCHS, ABORT_ON_BADAVWARP, ABORT_ON_NOPKMJD
     &    , ABORT_ON_BADZ, ABORT_ON_BADKCOR, ABORT_ON_BADSURVEY
     &    , ABORT_ON_MARGPDF0, ABORT_ON_TRESTCUT
     &    , ABORT_ON_DUPLCID, ABORT_ON_DUPLMJD, ABORT_ON_BADFILTER
     &    , H0_REF, OLAM_REF, OMAT_REF, W0_REF, DWDA_REF
     &    , USE_MWCOR
     &    , MXLC_PLOT, NCCID_PLOT, SNCCID_PLOT
     &    , MJDPERIOD_PLOT, MJDSHIFT_PLOT
     &    , DTOBS_MODEL_PLOT
     &    , MULTISEASON_OPTMASK, MULTISEASON_TGAP, zTOL_HELIO2CMB
     &    , MULTISEASON_NREJECT_OUTLIER, MULTISEASON_CHI2RED_ACTIVE
     &    , PHOTFLAG_DETECT, PHOTFLAG_TRIGGER
c
c Below are cut-variables defined in SNCUTS
c
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNCCID_IGNORE, SNCID_IGNORE_FILE, SNCID_IGNORE
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT
     &   ,cutwin_cid, cutwin_sntype
     &   ,cutwin_redshift, cutwin_redshift_err
     &   ,cutwin_ra, cutwin_dec
     &   ,cutwin_hostsep,   cutwin_Nepoch
     &   ,cutwin_snrmax,    cutwin_snrmax2, cutwin_nfield
     &   ,cutwin_mwebv,     cutwin_nseason_active
     &   ,cutwin_Trestmin,   cutwin_Trestmax
     &   ,cutwin_TrestRange, cutwin_Trest, cutwin_Tobs
     &   ,cutwin_Tgapmax,  cutwin_T0gapmax
     &   ,cutwin_Tobsmin,  cutwin_Tobsmax
     &   ,cutwin_peakmjd,  cutwin_mjd
c
     &   ,cutwin_psf, cutwin_zp,  CUTWIN_ZPADU, CUTWIN_ZPNPE
     &   ,cutwin_zperr, cutwin_photprob,  cutwin_errtest, cutwin_simpull
     &   ,cutwin_trest_trueflux, cutwin_nband_thresh
     &   ,cutwin_nfilt_snrmax,   cutwin_nfilt_snrmax2
     &   ,cutwin_nfilt_trestmin, cutwin_nfilt_trestmax
     &   ,cutwin_trest2, cutwin_nfilt_trest2
     &   ,cutwin_restlam, cutwin_lamrest, cutwin_lamobs
     &   ,cutwin_snr_nodetect
     &   ,PRIVATE_CUTWIN_STRING, PRIVATE_VARNAME_READLIST
     &   ,SIMVAR_CUTWIN_STRING
     &   ,EARLYLC_STRING, REQUIRE_EPOCHS_STRING, DUMP_STRING
c
     &   ,SNCUT_SNRMAX, SNCUT_HOST_SBFLUX
     &   ,EPCUT_SNRMIN, EPCUT_SKYSIG, EPCUT_PSFSIG
     &   ,MAGOBS_SHIFT_PRIMARY,  MAGOBS_SHIFT_ZP
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_ZP, FILTER_LAMSHIFT
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_COVERR
     &   ,FLUXERRMODEL_FILE,SIM_FLUXERRMODEL_FILE,FLUXERRMODEL_OPTMASK
     &   ,MAGCOR_FILE, SIM_MAGCOR_FILE, FUDGE_HOSTNOISE_FILE
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE, CUTWIN_NMJD_INCLUDE


c ---------- end of SNLCINP ---------

C +CDE,FILTCOM. inserted below by ypatchy. 

c filter bandpasses.
c Jan 16 2017: MXLAMBIN_FILT -> 4000 (was 3000) for JWST test

      INTEGER MXLAMBIN_FILT, MXLAMBIN_PRIM
      PARAMETER (
     &   MXLAMBIN_FILT = 4000   ! max number of lambda bins to store
     &  ,MXLAMBIN_PRIM = 4000  ! max lambda bins for primary
     &    )

c Define filter chars A-Z, a-z and 0-9, but do not change order of
c original FILTDEF characters so that we can still use older Kcor files.
c
      CHARACTER FILTDEF_STRING*100
      PARAMETER (FILTDEF_STRING =
     &  "ugrizYJHK UBVRIXy0123456789 abcdef " //  !  32
     &  "ACDEFGLMNOPQSTWZ " //                    ! +16
     &  "hjklmnopqstvwx "                         ! +14 = 62
cc     &  "~!@#$%^&*()-_=+[]{}<>,|;`'"  ! doesn't work for m0obs_[band] in tables
     &         )

      CHARACTER
     &   FILTOBS_NAME(MXFILT_ALL)*40   ! full filternames
     &  ,FILTREST_NAME(MXFILT_ALL)*40  ! full filternames
     &  ,SURVEY_FILT_NAME(MXFILT_ALL)*60    ! survey(s) for this band
     &  ,PRIMARY_NAME*40               ! name of primary
     &  ,NONSURVEY_FILTERS_ADD*80      ! NONSURVEY_FILTERS that were added

      LOGICAL
     &   LFILTDEF_OBS(MXFILT_ALL)  ! filter-trans define in KCOR file
     &  ,LFILTDEF_REST(MXFILT_ALL) ! filter-trans define in KCOR file
     &  ,LFILTDEF_NONSURVEY(MXFILT_ALL) ! part of NONSURVEY_FILTERS
     &  ,LFILTDEF_SNRMAX(MXFILT_ALL)    ! use for SNRMAX cut
     &  ,FREEZE_SURVEY_FILTERS     ! T=> do not re-read on 2nd version
     &  ,EXIST_BXFILT_OBS          ! T=> observer BX exists
     &  ,EXIST_BXFILT_REST         ! T=> idem for rest-frame

c define indices for legacy filters
      INTEGER
     &   IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &  ,IFILT_SDSS_i, IFILT_SDSS_z
     &  ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &  ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &  ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K

c define filter set for survey (observer) and for rest-frame.
c Each set goes 1 - NFILTDEF_[SURVEY,REST]

      INTEGER
     &   NFILTDEF_SURVEY          ! no. survey (obs) filters
     &  ,NFILTDEF_READ            ! no. filters to read (excludes BX)
     &  ,NFILTDEF_OBS        ! actual NFILTDEF from kcor file; should = NFILTDEF_SURVEY
     &  ,IFILTDEF_MAP_SURVEY(MXFILT_OBS)     ! IFILT_OBS vs. sparse filter index
     &  ,IFILTDEF_INVMAP_SURVEY(MXFILT_ALL) ! sparse index vs. IFILT_OBS
c
     &  ,NFILTDEF_REST                 ! no. rest-filts defined in Kcor file
     &  ,IFILTDEF_MAP_REST(MXFILT_OBS) ! IFILT_REST vs. sparse filter index
     &  ,IFILTDEF_INVMAP_REST(MXFILT_ALL) ! sparse index vs. IFILT_REST
c
     &  ,NFILTDEF_IGNORE_REST
     &  ,IFILTDEF_IGNORE_REST(MXFILT_OBS)  ! nearest rest-filters to ignore

c variables used in fitter; these variables are over-written
c in FITPAR_PREP for each SN

      INTEGER
     &   IFILT_REST_MAP(MXFILT_OBS)  ! idem for rest-frame filter
     &  ,NFILT_OBS_USEFIT                ! number of filters used in fit

      INTEGER*8
     &  IFILT_OBS_EVAL_MASK(2,MXFILT_ALL) ! set for each filter

      character FILTLIST_FIT_USE*64  ! filter-list USED each fit

c define filter properties using MXFILT_ALL
c Nov 12, 2010: split FILT_XXX into FILTOBS_XXX and FILTREST_XXX
c
      INTEGER
     &   NLAMBIN_FILTOBS(MXFILT_ALL)   ! number of bins per transmission curve
     &  ,NLAMBIN_FILTREST(MXFILT_ALL)  ! number of bins per transmission curve
     &  ,NLAMBIN_PRIMARY               ! lambda bins for primary spec


      REAL
     &   FILTOBS_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTOBS_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTOBS_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  ! corresponding lambda's (A)
     &  ,FILTOBS_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTOBS_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTOBS_LAMRANGE(2,MXFILT_ALL)       ! min,max range in obs-frames
     &  ,FILTOBS_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt_obs
     &  ,FILTOBS_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTOBS_ZPOFF_SNPHOT(MXFILT_ALL)     ! apply these ZPOFF to SNphot
     &  ,FILTOBS_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,FILTREST_TRANS(MXLAMBIN_FILT,MXFILT_ALL)   ! filter transmissions
     &  ,FILTREST_TRANSMAX(MXFILT_ALL)              ! max trans
     &  ,FILTREST_LAMBDA(MXLAMBIN_FILT,MXFILT_ALL)  !  lambda's (A)
     &  ,FILTREST_LAMAVG(MXFILT_ALL)           ! effective central lambda
     &  ,FILTREST_LAMRMS(MXFILT_ALL)           ! lambda-RMS
     &  ,FILTREST_LAMRANGE(2,MXFILT_ALL)       ! min,max range in rest-frames
     &  ,FILTREST_MAG_PRIMARY(MXFILT_ALL)      ! primary mag vs. ifilt
     &  ,FILTREST_ZPOFF_PRIMARY(MXFILT_ALL)    ! mag(native) - mag(synth)
     &  ,FILTREST_LAMSHIFT(MXFILT_ALL)         ! lambda shift per filter
c
     &  ,PRIMARY_FLUX(MXLAMBIN_PRIM)       ! primary spec for obs filters
     &  ,PRIMARY_LAM(MXLAMBIN_PRIM)

c for remap
      INTEGER NFILT_REPLACE, IFILTOBS_REPLACE(MXFILT_ALL)

      COMMON / FILTCOM / FILTOBS_NAME, FILTREST_NAME, SURVEY_FILT_NAME
     &   ,IFILT_SDSS_u, IFILT_SDSS_g, IFILT_SDSS_r
     &   ,IFILT_SDSS_i, IFILT_SDSS_z
     &   ,IFILT_BESS_U, IFILT_BESS_B, IFILT_BESS_V
     &   ,IFILT_BESS_R, IFILT_BESS_I, IFILT_BESS_BX
     &   ,IFILT_Y, IFILT_J, IFILT_H, IFILT_K
c
     &   ,NFILTDEF_SURVEY,  NFILTDEF_OBS, NFILTDEF_REST, NFILTDEF_READ
     &   ,FREEZE_SURVEY_FILTERS
     &   ,EXIST_BXFILT_OBS,       EXIST_BXFILT_REST
     &   ,IFILTDEF_MAP_SURVEY,    IFILTDEF_MAP_REST
     &   ,IFILTDEF_INVMAP_SURVEY, IFILTDEF_INVMAP_REST
     &   ,NFILTDEF_IGNORE_REST,   IFILTDEF_IGNORE_REST
     &   ,LFILTDEF_OBS, LFILTDEF_REST
     &   ,LFILTDEF_NONSURVEY, NONSURVEY_FILTERS_ADD
     &   ,LFILTDEF_SNRMAX
c
     &   ,NLAMBIN_FILTOBS, FILTOBS_TRANS, FILTOBS_TRANSMAX
     &   ,FILTOBS_LAMBDA, FILTOBS_LAMAVG, FILTOBS_LAMRMS
     &   ,FILTOBS_LAMRANGE
     &   ,FILTOBS_MAG_PRIMARY, FILTOBS_ZPOFF_PRIMARY
     &   ,FILTOBS_ZPOFF_SNPHOT, FILTOBS_LAMSHIFT
c
     &   ,NLAMBIN_FILTREST, FILTREST_TRANS, FILTREST_TRANSMAX
     &   ,FILTREST_LAMBDA,  FILTREST_LAMAVG, FILTREST_LAMRMS
     &   ,FILTREST_MAG_PRIMARY, FILTREST_ZPOFF_PRIMARY
     &   ,FILTREST_LAMSHIFT, FILTREST_LAMRANGE
c
     &   ,IFILT_REST_MAP
     &   ,FILTLIST_FIT_USE, NFILT_OBS_USEFIT
     &   ,PRIMARY_FLUX, PRIMARY_LAM, NLAMBIN_PRIMARY, PRIMARY_NAME
c
     &   ,NFILT_REPLACE, IFILTOBS_REPLACE

      COMMON / FILTCOM8 / IFILT_OBS_EVAL_MASK



      CHARACTER chis*80

      INTEGER
     &   hid, NBx, NBf, NHB(2), ipar, ix, i, LL, LF
     &  ,ifilt, ifilt_obs, NFUSE
     &  ,IPAR_LOOP1, IPAR_LOOP2
     &  ,NDIM1, NDIM2

c SNHIST args

      REAL*8
     &    xmin, xmax, dx, xcen, xbin, xtmp, x(2)
     &  , fmin, fmax, f, XHMIN(2), XHMAX(2)
     &  , chi2

      LOGICAL LBK2, LTEST, LDMPCHECK

c FCNSNLC args
      INTEGER IFLAG

      DOUBLE PRECISION
     &    GRAD8(MXFITPAR)
     &   ,FITSAVE8(MXFITPAR)
     &   ,FITPARLOC8(MXFITPAR)
     &   ,FITERRLOC8(MXFITPAR)
     &   ,chi8, USRFUN

      EXTERNAL USRFUN

C ------------------- BEGIN ---------------------

      NDIM1 = 1
      NDIM2 = 2

      print*,'  '
      print*,'    CALL HFUNMIN for CID = ', SNLC_CCID
      CALL FLUSH(6)

      IFLAG = FCNFLAG_USER
      NBx   = NBFITPAR  ! number of bins to plot chi2

      fmin  = -0.5
      fmax  = float(NFILT_OBS_USEFIT) + 0.5
      NBf   = int(fmax - fmin + 0.001 )

      DO ipar = 1, IPAR_MAX
         FITPARLOC8(ipar) = FITVAL(ipar,NFIT_ITERATION)
         FITERRLOC8(ipar) = FITERR(ipar,NFIT_ITERATION)
         FITSAVE8(ipar)   = FITPARLOC8(ipar)
      ENDDO


      IF ( IPAR_PLOTCHI2 .GT. 0 ) THEN
         IPAR_LOOP1 = IPAR_PLOTCHI2
         IPAR_LOOP2 = IPAR_PLOTCHI2
      ELSE
         IPAR_LOOP1 = 1
         IPAR_LOOP2 = IPAR_MAX
      ENDIF

      DO 100 ipar = IPAR_LOOP1, IPAR_LOOP2

         if ( FITERRLOC8(ipar) .LE. 0.0 ) goto 100

         print*,'      Plot chi2 around minimum of : ',
     &          PARNAME_STORE(ipar)

         xcen = FITPARLOC8(ipar)
         dx   = FITERRLOC8(ipar) * float(NFITSIG)

         dx = dx * SCALE_PLOTCHI2

         xmin =  -dx
         xmax =  +dx
         xbin = (xmax - xmin) / float(NBx)

c book chi2 vs. par - par(at min) vs. filter

        LL = INDEX(PARNAME_STORE(ipar),' ' ) - 1
        LF = INDEX(FILTLIST_FIT_USE,   ' ' ) - 1
        chis = 'FUN-chi2  vs.  [D]' // PARNAME_STORE(ipar)(1:LL) //
     &    ' and filters ' // FILTLIST_FIT_USE(1:LF) // char(0)

        hid      = HOFF + ipar
        NHB(1)   = NBX  ; NHB(2)   = NBF
        XHMIN(1) = xmin ; XHMIN(2) = fmin
        XHMAX(1) = xmax ; XHMAX(2) = fmax

        CALL SNHIST_INIT ( NDIM2, hid, chis,
     &             NHB, XHMIN, XHMAX, LEN(chis) )

         DO ix = 1, NBx

             LDMPCHECK = ( IPAR .EQ. IPAR_PLOTCHI2 )
cc     &          .and.    ( abs(xtmp-xcen) .LE. 10.*xbin )

             FCN_FITCHI2(0) = 0.0
             do ifilt = 1, NFILTDEF_SURVEY
               FCN_FITCHI2(ifilt) = 0.0

c check for filters to dump near the minimum
               ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
               if ( LDMPCHECK ) then
                 LDMPFCN(ifilt_obs) = LDMPFCN_PLOTCHI2(ifilt_obs)
                 LDMPFUN(ifilt_obs) = LDMPFUN_PLOTCHI2(ifilt_obs)
                 LDMPFCN(0)         = .true. ! xxx ?? 9.30.2021
               else
                 LDMPFCN(ifilt_obs) = .FALSE.
                 LDMPFUN(ifilt_obs) = .FALSE.
               endif

             enddo ! ifilt

            xtmp = Xcen + Xmin + ( float(ix) - 0.5 ) * xbin
            FITPARLOC8(ipar) = DBLE(xtmp)

            CALL FITINI_EPVAR(NFIT_ITERATION)
            CALL FCNSNLC(NFITPAR_MN,GRAD8,CHI8,FITPARLOC8,IFLAG,USRFUN)

            NFUSE = 0
            do 444 ifilt = 0, NFILTDEF_SURVEY

               if ( ifilt .GT. 0 ) then
                 ifilt_obs = IFILTDEF_MAP_SURVEY(ifilt)
                 if ( .NOT. USE_FILT(ifilt_obs) ) goto 444
                 NFUSE = NFUSE + 1
               endif

               x(1)     = xtmp - xcen
               x(2)     = float(NFUSE)
               chi2     = FCN_FITCHI2(ifilt)  ! chi2 excluding prior
               CALL SNHIST_FILL(NDIM2, HID, X, CHI2)
444          continue

         ENDDO  ! end ix loop over fitpar

         FITPARLOC8(ipar) = FITSAVE8(ipar)

100   CONTINUE  ! end if IPAR loop

      DO ifilt_obs = 1, MXFILT_ALL
         LDMPFCN(ifilt_obs) = .FALSE.
         LDMPFUN(ifilt_obs) = .FALSE.
      ENDDO
      print*, ' '

      RETURN
      END


C ================================
CDECK  ID>,  MONSIMEFF. 
      SUBROUTINE MON_SIMEFF
c
c Aug 2011: Plot SIMEFF vs. whatever.
c Feb 2013: replace HBOOK and HF2 with SNHIST_XXXX utils

      IMPLICIT NONE

c local var


C +CDE,SNDATCOM. inserted below by ypatchy. 


C +CDE,SNPAR. inserted below by ypatchy. 

      CHARACTER  SNTABLE_LIST_DEFAULT*60

c parameters used by snana code

      INTEGER
     &   MXVERS, MXSURVEY, MXSNLC,MXCID, MXCID_CHECK,MXEPOCH, MXITER
     &  ,MXFILT_ALL, MXFILT_OBS, MXFILT_REST, ONE
     &  ,MXFILT_KCOR, MXFILT_SNRMAX, MXEP_MODELGRID
     &  ,MXIDFIELD, MXFIELD_OVP, MXSEASON
     &  ,MXSNHOST, MXZPHOT_Q
     &  ,MXTABLE1D_KCOR,MXTABLE1D_LCMAG,MXTABLE1D_MWXT,MXTABLE1D_AVWARP
     &  ,MXZBIN_KCOR, MXTBIN_KCOR, MXAVBIN_KCOR, MXCBIN_AVWARP
     &  ,MNTYPE, MXTYPE, MXLISTNML, MXIGNORE_LIST
     &  ,MXVAR_PRIVATE, MXCUT_PRIVATE, MXVAR_TERSE, MXBIT_PHOTFLAG
     &  ,HOFF_NOCUTS, HOFF_CUTS, HOFF_SIM
     &  ,LUNHIS, LUNNML, LUNDAT, LUNTMP, LUNFIT, LUNPKMJD, LUNDMP
     &  ,LUNCID, LUNOUT
     &  ,LUNRES1, LUNRES2, LUNINTERP, LUNLIST, LUNIGNORE, LUNSALT2
     &  ,LUNLIST2, LUNIGNORE2
     &  ,ISTAGE_INIT, ISTAGE_RDSN, ISTAGE_CUTS, ISTAGE_USRANA
     &  ,ISTAGE_TEST
     &  ,INTERP_LINEAR, INTERP_SMOOTH, INTERP_ZSMOOTH
     &  ,MXERRTYPE, ERRTYPE_MINOS, ERRTYPE_PARAB, ERRTYPE_MARG
     &  ,ERRTYPE_BAD
     &  ,FCNFLAG_USER, FCNFLAG_FAST, FCNFLAG_LAST, FCNFLAG_USESIM
     &  ,FCNFLAG_PRIOR_ONLY, FCNFLAG_SIGMA_ONLY
     &  ,OPT_INTEGPDF_QUITCHI2, OPT_INTEGPDF_FULL
     &  ,OPT_SNXT_CCM89, OPT_SNXT_SJPAR
     &  ,OPT_MWCOLORLAW_DEFAULT, OPT_MWEBV_DEFAULT
     &  ,OPT_KCORERR_SJ, OPT_KCORERR_SJ5, OPT_KCORERR_SMOOTH
     &  ,OPTMASK_SNDATA_GLOBAL, OPTMASK_SNDATA_HEAD, OPTMASK_SNDATA_OBS
     &  ,OPTMASK_SNDATA_SPEC, OPTMASK_SNDATA_DUMP, OPTMASK_SNDATA_ALL
     &  ,OPTMASK_SNDATA_REQUIRE
     &  ,MXLINE_ARGS, MXKEY_ARGS, MXEPOCH_IGNORE
     &  ,NPAR_ANYLC, MXPAR_SIMSED, MXPAR_LCLIB
     &  ,MXLAMBIN_SNSED, MXCUTBIT
     &  ,OPT_FILTUPD_EACHSN, OPT_FILTUPD_MAP, OPT_FILTUPD_SAMEFILT
     &  ,OPT_FILTOBS, OPT_FILTREST
     &  ,ISTAT_READAGAIN, ISTAT_SKIP
     &  ,IDTABLE_MCMC
     &  ,ITABLE_SNANA,  ITABLE_FITRES, ITABLE_OUTLIER
     &  ,ITABLE_SNLCPAK, ITABLE_SPECPAK
     &  ,ITABLE_MODELSPEC, ITABLE_MARZ, MXTABLE
     &  ,IDTABLE_SNANA, IDTABLE_FITRES, IDTABLE_OUTLIER
     &  ,IDTABLE_MODELSPEC, IDTABLE_CIDPTR, IDTABLE_MARZ
     &  ,OPT_PARSTORE_TEXTTABLE
     &  ,MSKOPT_PARSE_WORDS_STRING
     &  ,MSKOPT_PARSE_WORDS_FILE
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE
c
     &  ,MODEL_STRETCH
     &  ,MODEL_STRETCH2
     &  ,MODEL_MLCS2k2
     &  ,MODEL_SNOOPY
     &  ,MODEL_SALT2, MODEL_SALT3
     &  ,MODEL_BAYESN
     &  ,MODEL_SIMSED
     &  ,MODEL_BYOSED
     &  ,MODEL_SNEMO
     &  ,MODEL_NON1A
     &  ,MODEL_LCLIB    ! Sep 2017
     &  ,MODEL_FIXMAG   ! force mags to user-value
     &  ,MXMODEL_INDEX
c
     &  ,MXCHAR_CCID, MXCHAR_VERSION, MXCHAR_SURVEY
     &  ,MXCHAR_PATH, MXCHAR_FILENAME, MXCHAR_MODELNAME
     &  ,MXCHAR_FIELDNAME, MXCHAR_PARNAME, MXCHAR_CUTNAME
     &  ,MXCHAR_FILEWORD,  MXCHAR_ARG, MXFILE_LIST
     &  ,FLAG_DOCANA_START, FLAG_DOCANA_END, FLAG_DOCANA_ERROR
c
     &  ,SNLCPAK_EPFLAG_FLUXDATA     ! DATA flux per epoch
     &  ,SNLCPAK_EPFLAG_REJECT   ! REJECT flag (1=> excluded from fit)
     &  ,SNLCPAK_EPFLAG_CHI2     ! data-fit chi2 per epoch
     &  ,SNLCPAK_EPFLAG_FITFUN   ! smooth  fitfun curve
     &  ,SNLCPAK_EPFLAG_FLUXSIM  ! SIM flux per epoch
     &  ,SNLCPAK_EPFLAG_FLUXREST ! rest-frame flux per epoch (optional)
     &  ,SNLCPAK_EPFLAG_KCOR     ! rest-frame kcor (Jan 2020)
     &  ,SNLCPAK_EPFLAG_AVWARP   ! rest-frame AVWARP
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST ! idem for sim truth
     &  ,SNLCPAK_EPFLAG_ERRCALC    ! FLUX-ERROR calculated from PSF,ZP,SKY
     &  ,SNLCPAK_BANDFLAG_PKFLUX   ! peak flux vs. filter
     &  ,SNLCPAK_BANDFLAG_PKMJD    ! peak MJD  vs. filter
     &  ,SNLCPAK_BANDFLAG_NDOF     ! Ndof vs. filter
     &  ,SNLCPAK_BANDFLAG_CHI2     ! chi2 vs. filter
c
     &  ,IFLAG_INI, IFLAG_ANA, IFLAG_END
     &  ,MASK_FLUXCOR_SNANA, MASK_FLUXERRCOR_SNANA
     &  ,EXIT_ERRCODE_SNANA, EXIT_ERRCODE_SNFIT, EXIT_ERRCODE_PSNID

      REAL*8
     &   ZERO8, ONE8, TEN8,  PI, LOGTEN
     &  ,PDFMIN, PDFMAX_EDGE, PDFMIN_GOOD
     &  ,KCORPACK
     &  ,XTMW_FRACERR
     &  ,MJDOFF
     &  ,ZEROPOINT_FLUXCAL_DEFAULT
     &  ,RV_MWCOLORLAW_DEFAULT
     &  ,CUTVAL_OPEN, IGNORE_HEADVAL

      REAL NULLVAL, MAG_SATURATE

      PARAMETER (                   ! BEGIN SNANA PARAMS
     &   SNTABLE_LIST_DEFAULT = 'SNANA  FITRES  LCPLOT'
     &  ,MXVERS        = 50         ! max number of versions to read
     &  ,MXSURVEY      = 100        ! max number of SURVEY_NAMEs to store
     &  ,MXITER        = 12         ! max # fit iterations
     &  ,MXSNLC        = 8000000    ! max number of SNe (fits format)
     &  ,MXIGNORE_LIST = 500        ! max size of IGNORE_LIST
     &  ,MXCID       = 299 999 999  ! max CID = 300 million -1 (9 digits)
     &  ,MXCID_CHECK =  99 999 999  ! MXCID to check duplicates
     &  ,MXEPOCH     = 30000      ! max number of filter-epochs per SN
     &  ,MXEP_MODELGRID = 200     ! max model grid for SNANA+SIM_MAGOBS table
     &  ,MXIDFIELD   = 200        ! max FIELD ID in SURVEY.DEF
     &  ,MXFIELD_OVP = 12         ! max number of overlapping fields
     &  ,MXSEASON    = 100        ! max number of seasons
     &  ,MXSNHOST    = 2          ! max number of host matches to read/write
     &  ,MXZPHOT_Q   = 20         ! max number of zphot quantiles (May 2022)
     &  ,MXVAR_PRIVATE = 40       ! max number of private variables
     &  ,MXCUT_PRIVATE = 10        ! max number of cuts on private var
     &  ,MXVAR_TERSE   = 30       ! max number of text-data  columms
     &  ,MXBIT_PHOTFLAG = 30      ! max number of PHOTFLAG bits
     &  ,MXLISTNML   = 52    ! max list size for some NML lists
     &  ,MXFILT_OBS  = 80    ! max number of used observer filters
     &  ,MXFILT_ALL  = 100   ! max number of all possible filter defs
     &  ,MXFILT_REST = 40    ! max number of rest-frame filter types (was 12)
     &  ,MXFILT_KCOR = MXFILT_REST ! max number of filters used in Kcor table
     &  ,MXFILT_SNRMAX =  8       ! no more than this many SNRMAX(filt) cuts
     &  ,MNTYPE       =   1       ! min sn "type"
     &  ,MXTYPE       = 1000      ! max sn "type"
     &  ,MXZBIN_KCOR  = 100       ! max # Z-bins for KCOR tables
     &  ,MXTBIN_KCOR  = 150       ! max # Epochs for KCOR tables
     &  ,MXAVBIN_KCOR = 100       ! max # AV bins for KCOR tables
     &  ,MXCBIN_AVWARP = 100      ! max color index for AVWARP table
     &  ,MXTABLE1D_KCOR   = 10 000 000  ! max number of KCOR bins
     &  ,MXTABLE1D_AVWARP =  1 500 000  ! max number of bins for AVWARP table
     &  ,MXTABLE1D_LCMAG  =  2 000 000  ! idem for LCMAG  table
     &  ,MXTABLE1D_MWXT   =  2 000 000  ! idem for MWXT table
     &  ,KCORPACK      = 1000.  ! store KCOR * KCORPACK as I*2
     &  ,XTMW_FRACERR  = 0.16   ! error on MW Xtinc is 16% of XTMW
c
     &  ,HOFF_NOCUTS = 100
     &  ,HOFF_CUTS   = 200
     &  ,HOFF_SIM    = 20000
     &  ,LUNHIS    = 21  ! LUN for hbook output file
     &  ,LUNNML    = 22  ! LUN for input namelist
     &  ,LUNDAT    = 23  ! LUN for data
     &  ,LUNTMP    = 24
     &  ,LUNOUT    = 25
     &  ,LUNFIT    = 26
     &  ,LUNLIST   = 27
     &  ,LUNIGNORE = 28
     &  ,LUNDMP    = 29
     &  ,LUNRES1   = 31  ! for DMP_FITRES
     &  ,LUNRES2   = 32
     &  ,LUNINTERP = 33  ! for FLUX,MAGs interpolated at SN,MJD
     &  ,LUNSALT2  = 34  ! for SALT2 dictFile
     &  ,LUNPKMJD  = 35
     &  ,LUNCID    = 36  ! reserved for reading SNCID_LIST_FILE
     &  ,LUNLIST2  = 47
     &  ,LUNIGNORE2= 48
     &  ,ISTAGE_INIT    = 10       ! init has finished
     &  ,ISTAGE_RDSN    = 20       ! SN have been read
     &  ,ISTAGE_CUTS    = 30       ! cuts have been applied
     &  ,ISTAGE_USRANA  = 40       ! USRANA has been called.
     &  ,ISTAGE_TEST    = 90       ! set for testing
     &  ,ZERO8          = 0.0
     &  ,ONE8           = 1.0
     &  ,ONE            = 1
     &  ,TEN8           = 10.0
     &  ,LOGTEN         = 2.302585092994
     &  ,INTERP_LINEAR  = 1    ! option flag to use linear DFINT
     &  ,INTERP_SMOOTH  = 2    ! option flag to use smoothing
     &  ,INTERP_ZSMOOTH = 3    ! linear DFINT, but smooth along z
c
     &  ,MXERRTYPE      = 10
     &  ,ERRTYPE_MINOS  = 1
     &  ,ERRTYPE_PARAB  = 2
     &  ,ERRTYPE_MARG   = 3  ! marginalized error
     &  ,ERRTYPE_BAD    = 6
C
     &  ,FCNFLAG_LAST     = 3    ! last MINUIT call
     &  ,FCNFLAG_USER     = 90   ! pass this IFLAG for user-FCNSNLC calls
     &  ,FCNFLAG_FAST     = 91   ! go as fast as possible (no LAST if-block)
     &  ,FCNFLAG_PRIOR_ONLY = 92
     &  ,FCNFLAG_SIGMA_ONLY = 93
     &  ,FCNFLAG_USESIM   = 99   ! pass this IFLAG to use SIM params
c
     &  ,PI     = 3.1415926535898
     &  ,PDFMIN      = 1.0E-5   ! used to speed up PDF integration
     &  ,PDFMAX_EDGE = 0.03     ! max allowed PDF value at edges
     &  ,PDFMIN_GOOD = 1.0E-4   ! PDF > PDFMIN_GOOD counts as good point
     &  ,OPT_INTEGPDF_QUITCHI2 = 2  ! abort FCNSNLC if chi2 > quitchi2
     &  ,OPT_INTEGPDF_FULL     = 1  ! do full FCNSNLC evaluation
c
     &  ,OPT_SNXT_CCM89   = 1  ! exact SN etinction using INIT_XTHOST
     &  ,OPT_SNXT_SJPAR   = 2  ! SN extinction with Jha's parameters
     &  ,OPT_KCORERR_SMOOTH = 1 ! use smooth half-Gaussian
     &  ,OPT_KCORERR_SJ     = 2   ! use Saurabh's Kcor error
     &  ,OPT_KCORERR_SJ5    = 5  ! x5 Saurabh's Kcor error
c
     &  ,OPTMASK_SNDATA_GLOBAL =  1
     &  ,OPTMASK_SNDATA_HEAD   =  2
     &  ,OPTMASK_SNDATA_OBS    =  4
     &  ,OPTMASK_SNDATA_SPEC   =  8
     &  ,OPTMASK_SNDATA_ALL    = 2+4+8  ! HEAD + OBS + SPEC
     &  ,OPTMASK_SNDATA_DUMP   = 32     ! flag to dump variable
     &  ,OPTMASK_SNDATA_REQUIRE= 64     ! flag to require variable
c
     &  ,RV_MWCOLORLAW_DEFAULT  = 3.1   ! A_V/E(B-V)
     &  ,OPT_MWCOLORLAW_DEFAULT = 94    ! ODonnel 94
     &  ,OPT_MWEBV_DEFAULT      =  1    ! whatever is in the data file
c
     &  ,MXLINE_ARGS      = 100  ! max number of command line args
     &  ,MXKEY_ARGS       =   5  ! max number of args per key
     &  ,ZEROPOINT_FLUXCAL_DEFAULT  = 27.5
     &  ,MXEPOCH_IGNORE   = 1000
     &  ,NPAR_ANYLC       = 10   ! for MNFIT_PKMJD
     &  ,MXPAR_SIMSED     = 100  ! max number of SIMSED parameters
     &  ,MXPAR_LCLIB      = 40   ! should be same as in genmag_LCLIB.h
     &  ,MXLAMBIN_SNSED   = 4000 ! Jan 2017: raised from 3000
     &  ,MXCUTBIT         = 64   ! max number of cut bits
c
     &  ,OPT_FILTUPD_EACHSN   = 1  ! default filter-updates
     &  ,OPT_FILTUPD_MAP      = 2  ! default filter-updates
     &  ,OPT_FILTUPD_SAMEFILT = 3  ! test: use same filter each SN
     &  ,OPT_FILTREST         = 1
     &  ,OPT_FILTOBS          = 2
     &  ,ISTAT_READAGAIN      = 7
     &  ,ISTAT_SKIP           = -1
c
     &  ,ITABLE_SNANA=1, ITABLE_FITRES=2, ITABLE_OUTLIER=3
     &  ,ITABLE_SNLCPAK=4, ITABLE_SPECPAK=5
     &  ,ITABLE_MODELSPEC=6, ITABLE_MARZ=7
     &  ,MXTABLE = 10
     &  ,IDTABLE_SNANA     = 7100  ! anaysis variables, every event
     &  ,IDTABLE_FITRES    = 7788  ! SNANA table + fit results, passing cuts
     &  ,IDTABLE_OUTLIER   = 7800  ! outlier fluxes (Mar 2021)
     &  ,IDTABLE_MODELSPEC = 8000  ! SALT2 model spectra from LC fit
     &  ,IDTABLE_MARZ      = 8100  ! MARZ table for spectra
     &  ,IDTABLE_CIDPTR    = 1600
     &  ,IDTABLE_MCMC      = 7711  ! obsolete ?
     &  ,OPT_PARSTORE_TEXTTABLE = 1  ! tag subset for TEXT table.
     &  ,MSKOPT_PARSE_WORDS_FILE    = 1   ! parse file
     &  ,MSKOPT_PARSE_WORDS_STRING  = 2   ! for store_PARSE_WORDS: string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMA   = 4  ! ignore comma for string
     &  ,MSKOPT_PARSE_WORDS_IGNORECOMMENT = 8  ! ignore comment lines
     &  ,MSKOPT_PARSE_WORDS_FIRSTLINE     = 16 ! read only 1st line of file
c
     &  ,MODEL_STRETCH    = 1
     &  ,MODEL_STRETCH2   = 2
     &  ,MODEL_MLCS2k2    = 3
     &  ,MODEL_SNOOPY     = 4
     &  ,MODEL_SALT2      = 6
     &  ,MODEL_SALT3      = 9 ! May 31 2019
     &  ,MODEL_BAYESN     = 13 ! Oct 7 2022: GN
     &  ,MODEL_SIMSED     = 7
     &  ,MODEL_BYOSED     = 8
     &  ,MODEL_SNEMO      = 9
     &  ,MODEL_NON1A      = 10
     &  ,MODEL_LCLIB      = 12
     &  ,MODEL_FIXMAG     = 20
     &  ,MXMODEL_INDEX    = 20
     &  ,NULLVAL          = -99999.
     &  ,IGNORE_HEADVAL   = -5555.
c
     &  ,MXCHAR_CCID       = 20   ! max len of CCID string (i.e, SN name)
     &  ,MXCHAR_VERSION    = 72   ! max len of VERSION_PHOTOMETRY
     &  ,MXCHAR_SURVEY     = 40   ! max len of SURVEY_NAME
     &  ,MXCHAR_PATH       = 160  ! max len of path
     &  ,MXCHAR_FILENAME   = 200  ! max len of filename with full path
     &  ,MXCHAR_MODELNAME  = 72   ! max len of model name
     &  ,MXCHAR_FIELDNAME  = 20   ! max len of field name
     &  ,MXCHAR_PARNAME    = 20   ! max len of parameter name
     &  ,MXCHAR_CUTNAME    = 300  ! to define cut names
     &  ,MXCHAR_FILEWORD   =  60  ! size of FILEWORD_LIST
     &  ,MXCHAR_ARG        = 800  ! max lenth of command line arg
     &  ,MXFILE_LIST       =  10  ! max number of files in input list
c
     &  ,FLAG_DOCANA_START  =  1  ! flags DOCUMENTATION key
     &  ,FLAG_DOCANA_END    =  2  ! flags DOCUMENTATION_END
     &  ,FLAG_DOCANA_ERROR  = -1  ! flags missing DOCANA keys

     &  ,SNLCPAK_EPFLAG_FLUXDATA    = 1    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_REJECT      = 2
     &  ,SNLCPAK_EPFLAG_CHI2        = 3
     &  ,SNLCPAK_EPFLAG_FITFUN      = 4
     &  ,SNLCPAK_EPFLAG_FLUXSIM     = 5    ! epoch-dependent
     &  ,SNLCPAK_EPFLAG_FLUXREST    = 6
     &  ,SNLCPAK_EPFLAG_KCOR        =   7
     &  ,SNLCPAK_EPFLAG_AVWARP      =   8
     &  ,SNLCPAK_EPFLAG_SIMFLUXREST = 9
     &  ,SNLCPAK_EPFLAG_ERRCALC     = 10
     &  ,SNLCPAK_BANDFLAG_NDOF    = 100
     &  ,SNLCPAK_BANDFLAG_PKFLUX  = 101  ! filter-dependent
     &  ,SNLCPAK_BANDFLAG_PKMJD   = 102
     &  ,SNLCPAK_BANDFLAG_CHI2    = 103
c
     &  ,IFLAG_INI=1, IFLAG_ANA=2, IFLAG_END=3
     &  ,MAG_SATURATE = -7.0    ! for sim only
     &  ,CUTVAL_OPEN  = 1.0E12  ! cutwin value to accept everything.
     &  ,MASK_FLUXCOR_SNANA    = 1
     &  ,MASK_FLUXERRCOR_SNANA = 2
c
     &  ,EXIT_ERRCODE_SNANA = 21
     &  ,EXIT_ERRCODE_SNFIT = 22
     &  ,EXIT_ERRCODE_PSNID = 23
     &      )

c physical constants

      REAL*8
     &   PARSEC, CLIGHT, PEAKMAG_AT_10PC
     &  ,Zat10pc
     &  ,OMAT_DEFAULT, OMATERR_DEFAULT
     &  ,OLAM_DEFAULT, OLAMERR_DEFAULT
     &  ,ORAD_DEFAULT
     &  ,H0_DEFAULT,   H0ERR_DEFAULT
     &  ,W0_DEFAULT,   W0ERR_DEFAULT
     &  ,DWDA_DEFAULT, DWDAERR_DEFAULT

      PARAMETER (
     &   PARSEC        = 3.085678E13  ! 1 parsec (km)
     &  ,CLIGHT        = 2.998E5      ! c (km/sec)
c
     &  ,H0_DEFAULT        = 70.0  ! standard value
     &  ,W0_DEFAULT        = -1.0
     &  ,DWDA_DEFAULT      =  0.0
     &  ,OMAT_DEFAULT      =  0.315  ! Planck 2018 (updated Mar 2020)
     &  ,OLAM_DEFAULT      =  0.685  ! idem
     &  ,ORAD_DEFAULT      =  1.2E-5
c
     &  ,H0ERR_DEFAULT        =  7.0
     &  ,W0ERR_DEFAULT        =  0.1
     &  ,DWDAERR_DEFAULT      =  0.0
     &  ,OMATERR_DEFAULT      =  0.03
     &  ,OLAMERR_DEFAULT      =  0.03
c
     &  ,PEAKMAG_AT_10PC   = -19.6
     &  ,Zat10pc           = 2.34E-9   ! magic redshift at 10 pc
     &  ,MJDOFF            = 0.0       ! 53000.
     &     )



C +CDE,SNFILECOM. inserted below by ypatchy. 

c Sep 9, 2010: Pulled out of SNDATACOM

      CHARACTER
     &   SNDATA_ROOT*(MXCHAR_PATH)
     &  ,SNANA_DIR*(MXCHAR_PATH)
     &  ,HOST_MACHINE*(MXCHAR_PATH)     ! name of host machine
     &  ,SNDATA_PATH*(MXCHAR_PATH)      ! subdir with data or sim files
     &  ,SNLIST_FILE*(MXCHAR_FILENAME)  ! input list of SNDATA Files
     &  ,SNREADME_FILE(MXVERS)*(MXCHAR_FILENAME)   ! name of EVERY README file
     &  ,SNDATA_FILE_CURRENT*(MXCHAR_FILENAME)     ! current file being read
     &  ,GLOBAL_BANNER*120
     &  ,SNDATA_PREFIX*(MXCHAR_FILENAME)  ! $SNDATA_ROOT/lcmerge/$VERSION
     &  ,C1ERR*88, C2ERR*88    ! generic error strings

      LOGICAL LFLAG_RDHEAD_ONLY

      COMMON / SNFILECOM /
     &   SNDATA_ROOT, SNANA_DIR, HOST_MACHINE, SNLIST_FILE
     &  ,SNDATA_FILE_CURRENT
     &  ,GLOBAL_BANNER, SNDATA_PREFIX, SNREADME_FILE, SNDATA_PATH
     &  ,C1ERR, C2ERR, LFLAG_RDHEAD_ONLY



C +CDE,CTRLCOM. inserted below by ypatchy. 

c control variables and counters.

      INTEGER
     &   ISTAGE_SNANA       ! current stage of processing
     &  ,NACCEPT_CUT(MXCUTBIT) ! Number of SN that pass each cut
     &  ,NACCEPT_CID           ! # SN with valid CID
     &  ,NACCEPT_TYPE          ! # SN with valid TYPE
     &  ,NACCEPT_Z             ! idem with valid redshift
     &  ,NACCEPT_ZERR          ! idem with valid redshift error
c
     &  ,NCALL_SNANA_DRIVER
c
     &  ,NPASSCUT_INCREMENT(-1:MXTYPE,100)  ! 100 > NCUTBIT_SNLC
     &  ,NPASSCUT_FIT(-1:MXTYPE)
     &  ,NVAR_NEARNBR          ! Number of NEARNBR variables to analyze
     &  ,NSTORE_MAGCOR         ! number of stored MAGCOR values
     &  ,NUSE_MAGCOR           ! number of used MAGCOR values
     &  ,SIGN_MAGCOR           ! add or subtract
     &  ,FORCEMASK_FLUXCOR   ! mask to force fluxCor, even if already applied
     &  ,EXIT_ERRCODE        ! used for abort

      INTEGER*8
     &   JTIME_START
     &  ,JTIME_LOOPSTART        ! time at start of fits with TIME()
     &  ,JTIME_LOOPEND          ! time and end

      LOGICAL
     &   DO_FIT
     &  ,DO_GETINFO        ! T=>GETINFO flag to print and quit
     &  ,DO_FLUXERRCALC    ! T => compute error from PSF,SKY & ZPT
     &  ,LSIM_SNANA        ! simulated with SNANA
     &  ,LSIM_MAGOBS   ! data-like, but with SIM_MAGOBS (e.g. fakes on images)
     &  ,ISJOB_SNANA          ! =T for snana.exe only.
     &  ,ISJOB_SNFIT          ! =T for snlc_fit or psnid
     &  ,ISJOB_PSNID
     &  ,ISJOB_SIM    ! either SNANA sim or fakes (LSIM_SNANA or LSIM_MAGOBS)
     &  ,ISJOB_BATCH  ! true if JOBSPLIT passed on command line (Aug 2020)
     &  ,REDUCE_STDOUT_BATCH   ! T => suppress stdout for JOBSPLIT(1)>1
     &  ,REFORMAT              ! T => a reformat option has been set
     &  ,REFORMAT_SNANA        ! T => reformat SNANA format
     &  ,REFORMAT_SAVE_BADEPOCHS ! include reject epochs (default=F)
     &  ,REFORMAT_SPECTRA_INCLUDE ! include spectra in data reformat (default=F)
     &  ,REFORMAT_SPECTRA_ONLY    ! reformat only spectra (OPT_REFORMAT_SPECTRA>0)
     &  ,REFORMAT_PRIVATE      ! T-> include private variables (default=T)
     &  ,REFORMAT_SIMTRUTH     ! T -> include SIM truth (default=T)
     &  ,STDOUT_UPDATE         ! T => update event to screen
     &  ,DOFUDGE_HOSTNOISE     ! T => FUDGE_HOSTNOISE_FILE is set
     &  ,DOFUDGE_NONLIN        ! T => NONLINEARITY_FILE is set
     &  ,DOFUDGE_FLUXERRMODEL  ! T => FLUXERRMODEL_FILE
     &  ,DOzSHIFT              ! T => apply a zSHIFT systematic
     &  ,ISCORRECT_SIGN_VPEC   ! T => data has correct VPEC sign (10/2020)
     &  ,DOFIX_WRONG_SIGN_VPEC ! T => flip VPEC sign
     &  ,UNIT_PSF_NEA          ! T => read NEA from data; else it's PSF
     &  ,FOUND_ATMOS           ! T=> found atmos variables (dRA,dDEC,AIRMASS)

      CHARACTER
     &    SNANA_VERSION*60        ! e.g., v11_04h-[commit-id]
     &   ,SNANA_VERSION_DATA*60   ! SNANA version used create FITS data
     &   ,REFORMAT_VERSION*(MXCHAR_VERSION)
     &   ,DATATYPE*12  ! e..g, 'DATA', 'FAKE', 'SNANA_SIM'

c global survey info
      CHARACTER
     &   SURVEY_NAME*(MXCHAR_SURVEY)
     &  ,SURVEY_NAME_LIST(MXSURVEY)*(MXCHAR_SURVEY) ! in SURVEY.DEF file
     &  ,SUBSURVEY_NAME*(MXCHAR_SURVEY)  ! e.g.,  SURVEY:  BLA(SUBSURVEY)
     &  ,SUBSURVEY_NAME_LIST*(MXCHAR_FILENAME) ! comma-sep list
     &  ,SURVEY_FILTERS*(MXFILT_ALL)  ! read from data file
     &  ,SURVEY_FIELDNAME(MXIDFIELD)*(MXCHAR_FIELDNAME) ! from SURVEY.DEF

      INTEGER
     &   NFIELD_SURVEY             ! number of survey fields in SURVEY.DEF
     &  ,SURVEY_IDFIELD(MXIDFIELD) ! integer ID for each field

      REAL
     &   ZEROPOINT_FLUXCAL(MXFILT_OBS)  ! defines calibrated flux

      INTEGER*4
     &   N_VERSION             ! number of photometry version to read
     &  ,N_SNLC_READ(MXVERS)   ! total numbrer of LC per version
     &  ,N_SNLC_PROC           ! number of SNLC processed with SNANA_DRIVER
     &  ,N_SNLC_CUTS           ! Number of SN after cuts (bookkeeping only)
     &  ,N_SNLC_SPEC           ! idem, but with 1 or more spectra
     &  ,N_SNLC_FIT            ! Number of fitted SN
     &  ,N_SNLC_FITCUTS        ! Number of fitted SN after fit cuts
     &  ,N_SNLC_COVFIX         ! Number of SN with fixed COV to be invertible
     &  ,N_SNHOST_ZSPEC        ! for YAML out file
     &  ,N_SNHOST_ZPHOT        ! idem
     &  ,N_DUPLICATE_CID       ! Number of duplicate CIDs
     &  ,N_DUPLICATE_MJD       ! Number of duplicate MJD+BAND (Jun 2017)
     &  ,NSTORE_DUPLICATE_MJD  ! Number stored
     &  ,N_SNFILE              ! # of SN files to read per version
     &  ,N_SNFILE_LAST         ! idem, as of last version
     &  ,ABSO_OFFSET           ! used to compute ABSO_INDEX
     &  ,ABSO_INDEX            ! absolute index (row or file number)
     &  ,NEPOCH_TOT            ! total number of epochs read from files
     &  ,NEPOCH_USE            ! total number of used epochs
     &  ,NEPOCH_CUT            ! total number of epochs passing cuts
     &  ,NEPOCH_BADPHOT        ! # epochs with bad PHOTFLAG (per event)
     &  ,NEPOCH_BADPHOT_SUM    ! # epochs with bad PHOTFLAG (summed)
     &  ,IDSURVEY              ! survey ID from SURVEY.DEF
     &  ,IDSUBSURVEY           ! =IDSURVEY unless subSurvey is different
     &  ,IDSURVEY_LIST(MXSURVEY) ! corresponds to SURVEY_NAME_LIST
     &  ,NSURVEY_LIST          ! size of SURVEY_NAME_LIST & IDSURVEY_LIST

      LOGICAL*1
     &    EXIST_KCOR_FILE
     &   ,EXIST_FILT(MXFILT_OBS)  ! T => at least one point per filt
     &   ,FOUND_SURVEY
     &   ,FORMAT_TEXT    ! ascii/txt for input data
     &   ,FORMAT_FITS    ! snfitsio for input data.

      INTEGER N_SNLC_PLOT
      LOGICAL MADE_LCPLOT  ! SAVE:  T if LC plot was made


      COMMON / CTRLCOM /
     &     SNANA_VERSION, SNANA_VERSION_DATA, REFORMAT_VERSION, DATATYPE
     &    ,SURVEY_NAME, SURVEY_NAME_LIST
     &    ,SUBSURVEY_NAME, SUBSURVEY_NAME_LIST
     &    ,NSURVEY_LIST, IDSURVEY, IDSUBSURVEY, IDSURVEY_LIST
     &    ,SURVEY_FILTERS
     &    ,SURVEY_FIELDNAME, SURVEY_IDFIELD, NFIELD_SURVEY
     &    ,ISJOB_SNANA, ISJOB_SNFIT, ISJOB_PSNID, ISJOB_SIM, ISJOB_BATCH
     &    ,REDUCE_STDOUT_BATCH
     &    ,ZEROPOINT_FLUXCAL
     &    ,NACCEPT_CUT, NACCEPT_CID, NACCEPT_TYPE
     &    ,NACCEPT_Z, NACCEPT_ZERR
     &    ,DO_FIT, DO_GETINFO, DO_FLUXERRCALC, NVAR_NEARNBR
     &    ,NSTORE_MAGCOR, NUSE_MAGCOR, SIGN_MAGCOR, FORCEMASK_FLUXCOR
     &    ,LSIM_SNANA, LSIM_MAGOBS
     &    ,ISTAGE_SNANA
     &    ,N_VERSION, N_SNLC_READ, N_SNLC_PROC, N_SNLC_CUTS, N_SNLC_SPEC
     &    ,N_SNLC_FIT, N_SNLC_FITCUTS, N_SNLC_COVFIX
     &    ,N_SNHOST_ZSPEC, N_SNHOST_ZPHOT
     &    ,N_SNFILE, N_SNFILE_LAST, N_DUPLICATE_CID
     &    ,N_DUPLICATE_MJD, NSTORE_DUPLICATE_MJD
     &    ,NEPOCH_TOT, NEPOCH_USE, NEPOCH_CUT
     &    ,NEPOCH_BADPHOT, NEPOCH_BADPHOT_SUM
     &    ,ABSO_OFFSET, ABSO_INDEX
     &    ,REFORMAT, REFORMAT_SPECTRA_INCLUDE, REFORMAT_SPECTRA_ONLY
     &    ,REFORMAT_SNANA, REFORMAT_PRIVATE
     &    ,REFORMAT_SAVE_BADEPOCHS, REFORMAT_SIMTRUTH
     &    ,STDOUT_UPDATE, ISCORRECT_SIGN_VPEC, DOFIX_WRONG_SIGN_VPEC
     &    ,DOFUDGE_HOSTNOISE, DOFUDGE_NONLIN, DOFUDGE_FLUXERRMODEL
     &    ,DOzSHIFT
     &    ,NCALL_SNANA_DRIVER, NPASSCUT_INCREMENT, NPASSCUT_FIT
     &    ,N_SNLC_PLOT, MADE_LCPLOT, UNIT_PSF_NEA, FOUND_ATMOS
     &    ,EXIT_ERRCODE

      COMMON / CTRLCOM8 / JTIME_START, JTIME_LOOPSTART, JTIME_LOOPEND

c logical *1 stuff

      COMMON / SNDATCOM1 / EXIST_KCOR_FILE, EXIST_FILT, FOUND_SURVEY
     &    ,FORMAT_TEXT, FORMAT_FITS

c SNTABLE control variables (May 2014)
      LOGICAL
     &   USE_TABLEFILE_HBOOK  ! write table in HBOOK format
     &  ,USE_TABLEFILE_ROOT   ! write table in ROOT format
     &  ,USE_TABLEFILE_TEXT   ! write table in TEXT format
     &  ,USE_TABLEFILE_MARZ   ! write table in MARZ/FITS format
     &  ,USE_TABLEFILE        ! T if either any of the above are set
     &  ,WRTABLEFILE_IAUC     ! T-> SNID -> IAUC (for writing tables)
     &  ,WRTABLEFILE_SIMVAR   ! T-> include SIM_XXX vars for simulation
     &  ,WRTABLEFILE_ZPHOT    ! T-> include ZPHOT info for PHOTOZ fit
     &  ,WRTABLEFILE_HOST_TEXT  ! T-> add HOST info in SNANA TEXT table
     &  ,WRTABLEFILE_HOST2_TEXT ! T-> add HOST and HOST2 info in SNANA TEXT table
     &  ,WRTABLEFILE_ERRCALC_TEXT! T-> add ERRCALC info in LCPLOT TEXT table

      INTEGER
     &   OPT_TABLE(MXTABLE)       ! option(s) for each table
     &  ,CUTMASK_SNANA_TABLE      ! select CUTFLAG_SNANA for SNANA table

      REAL
     &   PRESCALE_TABLE(MXTABLE)  ! table pre-scale (to reduce size)

      CHARACTER
     &   TEXTFORMAT_TABLE(MXTABLE)*8

c arrays for TABLE_FILTER_REMAP (Feb 2017)
      INTEGER NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE(MXFILT_ALL)
      CHARACTER FILTLIST_REMAP_TABLE*(MXFILT_ALL)

c Sep 23 2017: allow user codes to add private variables to SNTABLE
      INTEGER   NTABLEVAR_USER  ! e.g., set in snana_private.cra
      CHARACTER TABLEVARNAME_USER(MXVAR_PRIVATE)*40
      REAL      TABLEVALUE_USER(MXVAR_PRIVATE)

      COMMON / SNTABLECOM /
     &     USE_TABLEFILE_HBOOK, USE_TABLEFILE_ROOT
     &    ,USE_TABLEFILE_TEXT, USE_TABLEFILE_MARZ, USE_TABLEFILE
     &    ,OPT_TABLE, TEXTFORMAT_TABLE
     &    ,CUTMASK_SNANA_TABLE, WRTABLEFILE_IAUC, WRTABLEFILE_SIMVAR
     &    ,WRTABLEFILE_ZPHOT
     &    ,WRTABLEFILE_HOST_TEXT, WRTABLEFILE_HOST2_TEXT
     &    ,WRTABLEFILE_ERRCALC_TEXT
c
     &    ,NFILT_REMAP_TABLE, IFILTLIST_REMAP_TABLE
     &    ,FILTLIST_REMAP_TABLE
     &    ,NTABLEVAR_USER, TABLEVARNAME_USER
     &    ,TABLEVALUE_USER, PRESCALE_TABLE

c May 6, 2008: define lists for epochs to ignore

      INTEGER NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
      CHARACTER
     &   EPOCH_IGNORE_CCID(MXEPOCH_IGNORE)*(MXCHAR_CCID)
     &  ,EPOCH_IGNORE_FILT(MXEPOCH_IGNORE)*4
     &  ,EPOCH_IGNORE_LASTFILE*(MXCHAR_FILENAME)

      REAL*8
     &   EPOCH_IGNORE_MJD(MXEPOCH_IGNORE)

      COMMON / EPIGNORE_COM / NEPOCH_IGNORE, NEPOCH_IGNORE_WRFITS
     &  ,EPOCH_IGNORE_CCID, EPOCH_IGNORE_FILT, EPOCH_IGNORE_LASTFILE
      COMMON / EPIGNORE_COM8 / EPOCH_IGNORE_MJD


      REAL*8  DUPLICATE_MJDLIST(200)
      COMMON / DUPMJDCOM / DUPLICATE_MJDLIST


C +CDE,SNLCCOM. inserted below by ypatchy. 

c Main common block variables for light curves and
c analysis-related variables.

      INTEGER
     &   SNLC_CID                  ! integer CID
     &  ,INDEX_CID_MATCH           ! ISN index from SNCID_LIST_FILE
     &  ,ISNLC_SNRECON_USE(MXEPOCH)  ! 1 -> epoch used in SNRECON
     &  ,ISNLC_PHOTFLAG(MXEPOCH)     ! photomety flags
     &  ,ISNLC_zFLAG                 ! zspec-quality flag (May 2020), data only
     &  ,ISNLC_zSOURCE               ! mask indicating the source of redshift
     &  ,ISNLC_LENCCID     ! char-len of CCID
     &  ,ISNLC_LENIAUC     ! char-len of IAUC name
     &  ,ISNLC_VERSION     ! photometry version index vs. ISN
     &  ,ISNLC_TYPE        ! type (120=confirmed Ia, etc ...)
     &  ,ISNLC_IFILE       ! ifile index, text format only
     &  ,ISNLC_IFILT_OBS(MXEPOCH) ! filt-index for each epoch/SN
     &  ,ISNLC_NEWMJD_HEAD   ! Number of NEWMJDs in header
     &  ,ISNLC_NEWMJD_FOUND  ! Number of NEWMJDs found in file
     &  ,ISNLC_NEWMJD_STORE  ! Number of NEWMJDs stored
     &  ,ISNLC_NEWMJD_CUTS   ! Number of NEWMJDs after cuts
     &  ,ISNLC_EPOCH_RANGE_NEWMJD(2,MXEPOCH)
     &  ,ISNLC_NFILT_NEWMJD(MXEPOCH)   ! # observed filters per NEWMJD
     &  ,ISNLC_NFILT_SNRMAX      ! number of filters passing SNR cut
     &  ,ISNLC_NFILT_SNRMAX2     ! idem for 2nd SNRMAX cut
     &  ,ISNLC_NFILT_TRESTMIN     ! Nfilt passing TRESTMIN cut
     &  ,ISNLC_NFILT_TRESTMAX     ! idem for TRESTMAX
     &  ,ISNLC_NFILT_TREST2       ! Nfilt passing CUTWIN_TREST2 cut
     &  ,ISNLC_NEPOCH_FOUND  ! actual number of epochs found
     &  ,ISNLC_NEPOCH_STORE  ! number of epochs stored in memory
     &  ,ISNLC_NEPOCH_USE       ! used after PHOTMASK cuts
     &  ,ISNLC_NEPOCH_PHOTPROB  ! NEPOCH with PHOTPROB >= 0
     &  ,ISNLC_NEPOCH_DETECT    ! NEPOCH with detection
     &  ,ISNLC_NEPOCH_FILT(MXFILT_OBS)  ! NEPOCH vs. filter
     &  ,ISNLC_NEPOCH_PRESN(MXFILT_OBS) ! pre-explosion epochs
     &  ,ISNLC_NMJD_INCLUDE             ! NOBS in CUTWIN_MJD_INCLUDE window
c
     &  ,ISNLC_FAKE             ! => real data, else it's a fake
     &  ,ISNLC_CCDNUM(MXEPOCH)  ! read from header (May 2017)
     &  ,ISNLC_IMGNUM(MXEPOCH)  ! Oct 2021: IMAGE NUNBER (e.g., EXPNUM, VISIT_ID)
     &  ,ISNLC_IDFIELD(MXEPOCH) ! integer field id
     &  ,ISNLC_NFIELD_OVP       ! number of fields (>=2 for overlap)
     &  ,ISNLC_CUTFLAG_REQEP        ! idem
     &  ,ISNLC_CUTFLAG_PRIVATE      ! idem for private var cuts
     &  ,ISNLC_CUTFLAG_SIMVAR       ! idem for SIMVAR cuts
     &  ,ISNLC_WRMASK_FLUXCOR_SNANA   ! write if fudges applied to data
     &  ,ISNLC_RDMASK_FLUXCOR_SNANA   ! read if SNANA fudges applied to data

      REAL*8
     &   SNLC8_RA        ! RA   vs. SN
     &  ,SNLC8_DEC       ! DEC  vs. SN
     &  ,SNLC8_MJD(MXEPOCH)  ! MJD for each epoch
     &  ,SNLC8_MJDMIN        !   min MJD among all measurements
     &  ,SNLC8_MJDMAX        !   max MJD ...
     &  ,SNLC8_MJD_TRIGGER   ! MJD of trigger bit (see PHOTFLAG_TRIGGER)
     &  ,SNLC8_MJD_DETECT_FIRST
     &  ,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL(MXEPOCH) ! to call functions requiring double
     &  ,SNLC8_FLUXCAL_ERRTOT(MXEPOCH)

      REAL
     &   SNLC_ZHELIO        ! redshift used for final analysis
     &  ,SNLC_ZHELIO_ERR    ! error on above
     &  ,SNLC_ZCMB          ! redshift used for final analysis
     &  ,SNLC_ZCMB_ERR      ! error on above
     &  ,SNLC_ZHD           ! redshift used for Hubble diagram
     &  ,SNLC_ZHD_ERR       ! error on above
     &  ,SNLC_ZSN           ! redshift of SN only (ignoring host-z)
     &  ,SNLC_ZSN_ERR       ! error on above
     &  ,SNLC_REDSHIFT      ! redshift used for light curve fit
     &  ,SNLC_REDSHIFT_ERR  ! error on above
     &  ,SNLC_VPEC          ! pec. velocity
     &  ,SNLC_VPEC_ERR      ! error on above
     &  ,SNLC_ZPEC
     &  ,SNLC_ZPEC_ERR
     &  ,SNLC_Trestmin  ! earliest epoch, rest frame days since peak
     &  ,SNLC_Trestmax  ! latest   epoch, rest frame days since peak
     &  ,SNLC_TrestRange
     &  ,SNLC_Tobsmin   ! earliest epoch, obs frame days since peak
     &  ,SNLC_Tobsmax   ! latest   epoch, obs frame days since peak
     &  ,SNLC_TGAPMAX     ! max gap within TREST-range
     &  ,SNLC_T0GAPMAX    ! max gap near peak
     &  ,SNLC_SNRMAX_FILT(0:MXFILT_OBS)   ! max S/N per filter/SN
     &  ,SNLC_SNRMAX_SORT(MXFILT_OBS)     ! 1st, 2nd ... SNRMAX by filt
     &  ,SNLC_FLUXCALMAX(MXFILT_OBS)    ! max flux per filter/SN
     &  ,SNLC_FLUXCALMAX_ERR(MXFILT_OBS)  ! uncertainty on above
     &  ,SNLC_SNANAFIT_PEAKMJD     ! SNANA-estimate of PEAKKMJD
     &  ,SNLC_SNANAFIT_PEAKMJD_FITPAR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_SNANAFIT_PEAKMJD_FITERR(MXFILT_OBS,NPAR_ANYLC)
     &  ,SNLC_PHOTPROB(MXEPOCH)   ! generic 'fit probability' per epoch
     &  ,SNLC_PHOTPROB_MIN        ! min photprob for PHOTPROB>0
     &  ,SNLC_TOBS(MXEPOCH)        ! MJD-SET_PEAKMJD
     &  ,SNLC_TREST(MXEPOCH)       !  MJD-SET_PEAKMJD)/(1+z)
     &  ,SNLC_GAIN(MXEPOCH)      ! e/AUD
     &  ,SNLC_RDNOISE(MXEPOCH)   ! read noise per pix, e-
     &  ,SNLC_PIXSIZE            ! pixel size
     &  ,SNLC_NXPIX              ! total number of X-pixels (Aug 7 2014)
     &  ,SNLC_NYPIX              ! total number of Y-pixels
     &  ,SNLC_XPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_YPIX(MXEPOCH)      ! pixel location
     &  ,SNLC_AREAFRAC(MXEPOCH)  ! area-frac contained by XPIX,YPIX
     &  ,SNLC_AREAFRAC_AVG       ! average over epochs (May 2020)
     &  ,SNLC_dRA(MXEPOCH)       ! RA(obs) - RA_AVG(band)
     &  ,SNLC_dDEC(MXEPOCH)
     &  ,SNLC_AIRMASS(MXEPOCH)
     &  ,SNLC_MWEBV              ! Milky Way Galactic E(B-V)
     &  ,SNLC_MWEBV_ERR          ! error on above
     &  ,SNLC_SKYSIG(MXEPOCH)    ! sigma on above
     &  ,SNLC_SKYSIG_T(MXEPOCH)  ! sigma on template run
     &  ,SNLC_PSF_SIG1(MXEPOCH)  ! sigma, pixels
     &  ,SNLC_PSF_SIG2(MXEPOCH)
     &  ,SNLC_PSF_RATIO(MXEPOCH)
     &  ,SNLC_PSF_FWHM_ARCSEC(MXEPOCH)
     &  ,SNLC_PSF_NEA(MXEPOCH)     ! Noise-equivalent area (pixels)
     &  ,SNLC_FLUX_NSIG(MXEPOCH)   ! significance
     &  ,SNLC_FLUXCAL_OFF(MXFILT_OBS)    ! add SN light from template
     &  ,SNLC_FLUXCAL_ERRCALC(MXEPOCH)   ! calc a-la simulation
     &  ,SNLC_FLUXCAL_HOSTERRCALC(MXEPOCH)   ! idem for host error
     &  ,SNLC_FLUXCAL(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTOT(MXEPOCH)
     &  ,SNLC_FLUXCAL_ERRTEST(MXEPOCH)   ! ERRCALC/ERRTRUE (Nov 2019
     &  ,SNLC_FLUXCAL_FIT(MXEPOCH)       ! used for outlier table
     &  ,SNLC_FLUXCAL_ERR_FIT(MXEPOCH)   ! idem
     &  ,SNLC_FLUXCAL_ERRTOT_FIT(MXEPOCH)   ! sqrt[cov(data)+cov(fit)]
     &  ,SNLC_MAG(MXEPOCH)
     &  ,SNLC_MAG_ERRPLUS(MXEPOCH)
     &  ,SNLC_MAG_ERRMINUS(MXEPOCH)
     &  ,SNLC_ZEROPT(MXEPOCH)
     &  ,SNLC_ZEROPT_ERR(MXEPOCH)
     &  ,SNLC_ZEROPT_forCUT(MXEPOCH)  ! depends on CUTWIN_ZPADU or CUTWIN_ZPNPE
     &  ,SNLC_DLMAG                   ! 5*log10(10pc/DL)
     &  ,SNLC_SKYFLUXCAL(MXEPOCH)     ! calculated sky fluxcal/pixel
     &  ,SNLC_MWXT_MAG(MXFILT_OBS)        ! mag stellar extinct
     &  ,SNLC_MWXT_FLUXFRAC(MXFILT_OBS)   ! same for flux (< 1)
     &  ,SNLC_MWXT_MAGERR(MXFILT_OBS)     ! Galactic mag err per filter
     &  ,SNLC_SEARCH_PEAKMJD            ! external PEAKMJD
     &  ,SNLC_DTOBS(MXEPOCH)            ! time since last obs
     &  ,SNLC_DTOBS_SAMEFILT(MXEPOCH)   ! idem, but same filter
     &  ,SNLC_TLIVE_DETECT     ! MJD(last detection) - MJD(1st detection)

      INTEGER
     &   NSEASON_TOT     ! total number of seasons
     &  ,NSEASON_ACTIVE  ! total number of active seasons

      REAL*4
     &   MULTISEASON_CHI2RED(MXSEASON) ! borrow another 'MX' param
     &  ,MULTISEASON_AVGFLUX(MXSEASON)
     &  ,MULTISEASON_MJDMIN(MXSEASON)
     &  ,MULTISEASON_MJDMAX(MXSEASON)

      CHARACTER
     &   SNLC_CCID*(MXCHAR_CCID)      ! char CID
     &  ,SNLC_IAUC*(MXCHAR_CCID)
     &  ,SNLC_CASTCID*8             ! = 'INT' or 'CHAR' to indicate cast
     &  ,SNLC_FIELD(MXEPOCH)*(MXCHAR_FIELDNAME)    ! char field name
     &  ,SNLC_FIELD_OVPLIST(MXFIELD_OVP)*(MXCHAR_FIELDNAME)  ! sparse list of overlap fields
     &  ,SNLC_FIELDLIST*(MXCHAR_FIELDNAME) ! e.g., '82S', '82N+82S'

      COMMON / SNLC8COM /
     &   SNLC8_RA, SNLC8_DEC
     &  ,SNLC8_MJD, SNLC8_MJDMIN, SNLC8_MJDMAX
     &  ,SNLC8_MJD_TRIGGER,SNLC8_MJD_DETECT_FIRST,SNLC8_MJD_DETECT_LAST
     &  ,SNLC8_FLUXCAL, SNLC8_FLUXCAL_ERRTOT

      COMMON / SNLCCOM /
     &     SNLC_CID, SNLC_CCID,  SNLC_CASTCID, SNLC_IAUC
     &    ,INDEX_CID_MATCH
     &    ,SNLC_FIELD, SNLC_FIELD_OVPLIST, SNLC_FIELDLIST
     &    ,SNLC_SNANAFIT_PEAKMJD
     &    ,SNLC_SNANAFIT_PEAKMJD_FITPAR
     &    ,SNLC_SNANAFIT_PEAKMJD_FITERR
     &    ,SNLC_SEARCH_PEAKMJD
     &    ,SNLC_ZHELIO, SNLC_ZHELIO_ERR
     &    ,SNLC_ZCMB,   SNLC_ZCMB_ERR, SNLC_ZHD, SNLC_ZHD_ERR
     &    ,SNLC_ZSN, SNLC_ZSN_ERR
     &    ,SNLC_REDSHIFT, SNLC_REDSHIFT_ERR
     &    ,SNLC_VPEC, SNLC_VPEC_ERR, SNLC_ZPEC, SNLC_ZPEC_ERR
     &    ,SNLC_TRESTMIN, SNLC_TRESTMAX, SNLC_TrestRange, SNLC_TREST
     &    ,SNLC_TGAPMAX,  SNLC_T0GAPMAX
     &    ,SNLC_Tobsmin, SNLC_Tobsmax, SNLC_TOBS
     &    ,SNLC_SNRMAX_FILT, SNLC_SNRMAX_SORT
     &    ,SNLC_FLUXCALMAX, SNLC_FLUXCALMAX_ERR
     &    ,SNLC_PHOTPROB, SNLC_PHOTPROB_MIN
     &    ,SNLC_GAIN, SNLC_RDNOISE
     &    ,SNLC_MWXT_MAG, SNLC_MWXT_FLUXFRAC, SNLC_MWXT_MAGERR
     &    ,SNLC_MWEBV, SNLC_MWEBV_ERR
     &    ,SNLC_XPIX, SNLC_YPIX, SNLC_PIXSIZE, SNLC_NXPIX, SNLC_NYPIX
     &    ,SNLC_AREAFRAC_AVG, SNLC_AREAFRAC
     &    ,SNLC_dRA, SNLC_dDEC, SNLC_AIRMASS
     &    ,SNLC_SKYSIG,  SNLC_SKYSIG_T
     &    ,SNLC_PSF_SIG1, SNLC_PSF_SIG2, SNLC_PSF_RATIO
     &    ,SNLC_PSF_NEA, SNLC_PSF_FWHM_ARCSEC
c
     &    ,SNLC_FLUX_NSIG, SNLC_FLUXCAL_OFF
     &    ,SNLC_FLUXCAL_ERRCALC, SNLC_FLUXCAL_ERRTEST
     &    ,SNLC_FLUXCAL_HOSTERRCALC
     &    ,SNLC_FLUXCAL, SNLC_FLUXCAL_ERRTOT
     &    ,SNLC_FLUXCAL_FIT,SNLC_FLUXCAL_ERR_FIT,SNLC_FLUXCAL_ERRTOT_FIT
     &    ,SNLC_MAG, SNLC_MAG_ERRPLUS, SNLC_MAG_ERRMINUS
     &    ,SNLC_ZEROPT, SNLC_ZEROPT_ERR, SNLC_ZEROPT_forCUT
     &    ,SNLC_SKYFLUXCAL, SNLC_DLMAG
     &    ,SNLC_DTOBS, SNLC_DTOBS_SAMEFILT

      COMMON / ISNCOM /
     &     ISNLC_VERSION, ISNLC_SNRECON_USE, ISNLC_PHOTFLAG
     &    ,ISNLC_TYPE, ISNLC_zFLAG, ISNLC_zSOURCE, ISNLC_IFILE
     &    ,ISNLC_LENCCID, ISNLC_LENIAUC
     &    ,ISNLC_NFILT_NEWMJD, ISNLC_IFILT_OBS
     &    ,ISNLC_NEWMJD_HEAD, ISNLC_NEWMJD_FOUND, ISNLC_NEWMJD_STORE
     &    ,ISNLC_NEWMJD_CUTS, ISNLC_EPOCH_RANGE_NEWMJD
     &    ,ISNLC_NEPOCH_FOUND, ISNLC_NEPOCH_STORE
     &    ,ISNLC_NEPOCH_USE, ISNLC_NEPOCH_PHOTPROB
     &    ,ISNLC_NEPOCH_FILT,  ISNLC_NEPOCH_PRESN, ISNLC_NMJD_INCLUDE
     &    ,ISNLC_NEPOCH_DETECT, SNLC_TLIVE_DETECT
     &    ,ISNLC_FAKE, ISNLC_CCDNUM, ISNLC_IMGNUM
     &    ,ISNLC_NFILT_SNRMAX, ISNLC_NFILT_SNRMAX2
     &    ,ISNLC_NFILT_TRESTMIN, ISNLC_NFILT_TRESTMAX
     &    ,ISNLC_NFILT_TREST2
     &    ,ISNLC_IDFIELD, ISNLC_NFIELD_OVP
     &    ,ISNLC_CUTFLAG_REQEP
     &    ,ISNLC_CUTFLAG_PRIVATE
     &    ,ISNLC_CUTFLAG_SIMVAR
     &    ,ISNLC_WRMASK_FLUXCOR_SNANA, ISNLC_RDMASK_FLUXCOR_SNANA

c - - - - -  ADDCOL stuff - - - - - - -
c ADDCOL arrays are loaded with original filter indices,
c or with REMAPed filter indices. Allows using unique
c pointer for calls to SNTABLE_ADDCOL.

      CHARACTER
     &    ADDCOL_FILTERS*(MXFILT_ALL) ! SURVEY_FILTERS

      REAL
     &    ADDCOL_SNHOST_MAGOBS(MXFILT_ALL,MXSNHOST)
     &   ,ADDCOL_SNHOST_SBFLUXCAL(MXFILT_ALL)
     &   ,ADDCOL_SNHOST_SBMAG(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX(MXFILT_ALL)
     &   ,ADDCOL_FLUXCALMAX_ERR(MXFILT_ALL)
     &   ,ADDCOL_CHI2_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_SNRMAX(MXFILT_ALL)
     &   ,ADDCOL_XTMW(MXFILT_ALL)
     &   ,ADDCOL_PROB_TRUEFLUX(MXFILT_ALL)

      INTEGER
     &    ADDCOL_NDOF_FITPKMJD(MXFILT_ALL)
     &   ,ADDCOL_NDOF_TRUEFLUX(MXFILT_ALL)

      COMMON / ADDCOL_FILTERCOM /
     &   ADDCOL_FILTERS, ADDCOL_SNHOST_MAGOBS
     &  ,ADDCOL_SNHOST_SBFLUXCAL, ADDCOL_SNHOST_SBMAG
     &  ,ADDCOL_FLUXCALMAX, ADDCOL_FLUXCALMAX_ERR
     &  ,ADDCOL_CHI2_FITPKMJD, ADDCOL_NDOF_FITPKMJD
     &  ,ADDCOL_SNRMAX, ADDCOL_XTMW
     &  ,ADDCOL_PROB_TRUEFLUX, ADDCOL_NDOF_TRUEFLUX


c - - - -- MULTI-SEASON STUFF - - - -
      COMMON / MULTISEASONCOM / NSEASON_TOT, NSEASON_ACTIVE
     &  ,MULTISEASON_CHI2RED, MULTISEASON_AVGFLUX
     &  ,MULTISEASON_MJDMIN,  MULTISEASON_MJDMAX


C +CDE,SNCUTS. inserted below by ypatchy. 

c Define cut-window for each variables
c and cut-mask for each epoch.
c User must fill cutwin_XXX arrays in main routine.

      INTEGER
     &   CUTBIT_CID, CUTBIT_SNTYPE
     &  ,CUTBIT_REDSHIFT, CUTBIT_REDSHIFT_ERR
     &  ,CUTBIT_RA,  CUTBIT_DEC
     &  ,CUTBIT_HOSTSEP
     &  ,CUTBIT_Trestmin, CUTBIT_Trestmax, CUTBIT_TrestRange
     &  ,CUTBIT_TREST2
     &  ,CUTBIT_Tgapmax,  CUTBIT_T0gapmax
     &  ,CUTBIT_Tobsmin,  CUTBIT_Tobsmax
     &  ,CUTBIT_SEARCH           ! sim only
     &  ,CUTBIT_PEAKMJD
     &  ,CUTBIT_NMJD_INCLUDE    ! Aug 11 2015
     &  ,CUTBIT_NEPOCH
     &  ,CUTBIT_SNRMAX         ! global SNRMAX cut; any filter(s)
     &  ,CUTBIT_SNRMAX2        ! 2nd global SNRMAX cut; any filter(s)
     &  ,CUTBIT_NFIELD         ! cut on number of fields used by SN
     &  ,CUTBIT_MWEBV          ! cut on Galactic extinct (May 8 2012)
     &  ,CUTBIT_NSEASON_ACTIVE ! Nseason with activity
     &  ,CUTBIT_REQEP          ! required epochs (to select short events)
     &  ,CUTBIT_PRIVATE        ! all private-var cuts together (Nov 3 2014)
     &  ,CUTBIT_SIMVAR         ! SIMVAR cuts
     &  ,CUTBIT_OFFSET_SBFLUX  ! host surface brightness
     &  ,CUTBIT_OFFSET_SNRMAX  ! SNRMAX cuts in each filter
     &  ,CUTBIT_MJD_MARKER     ! things above do NOT depend on epoch
     &  ,CUTBIT_PSF,  CUTBIT_ZP, CUTBIT_ZPERR
     &  ,CUTBIT_PHOTPROB
     &  ,CUTBIT_TREST, CUTBIT_TOBS, CUTBIT_MJD
     &  ,CUTBIT_ERRTEST          ! epoch cut on ERRCALC/ERRTRUE
     &  ,CUTBIT_SIMPULL          ! cut on (F-F_true)/sigma_F
     &  ,CUTBIT_TREST_TRUEFLUX2  ! for sim or fakes, require valid flux
     &  ,CUTBIT_NFILT_SNRMAX
     &  ,CUTBIT_NFILT_SNRMAX2
     &  ,CUTBIT_NFILT_TRESTMIN
     &  ,CUTBIT_NFILT_TRESTMAX
     &  ,CUTBIT_NFILT_TREST2
     &  ,CUTBIT_OFFSET
     &  ,NCUTBIT
     &  ,NCUTBIT_SNLC

      PARAMETER (
     &   CUTBIT_CID            = 1
     &  ,CUTBIT_SNTYPE         = 2
     &  ,CUTBIT_REDSHIFT       = 3
     &  ,CUTBIT_REDSHIFT_ERR   = 4
     &  ,CUTBIT_RA             = 5
     &  ,CUTBIT_DEC            = 6
     &  ,CUTBIT_HOSTSEP        = 7
     &  ,CUTBIT_TrestMIN       = 8
     &  ,CUTBIT_TrestMAX       = 9
     &  ,CUTBIT_TrestRange     = 10  ! Dec 2017 (TrestMax-TrestMin)
     &  ,CUTBIT_Trest2         = 11  ! Oct 2012
     &  ,CUTBIT_Tgapmax        = 12
     &  ,CUTBIT_T0gapMAX       = 13
     &  ,CUTBIT_TobsMIN        = 14
     &  ,CUTBIT_TobsMAX        = 15
     &  ,CUTBIT_PEAKMJD        = 16
     &  ,CUTBIT_NMJD_INCLUDE   = 17
     &  ,CUTBIT_NEPOCH         = 18  ! total # of measurements
     &  ,CUTBIT_SEARCH         = 19  ! found by search (SIM only)
     &  ,CUTBIT_NFILT_SNRMAX   = 20
     &  ,CUTBIT_NFILT_SNRMAX2  = 21
     &  ,CUTBIT_NFILT_TRESTMIN = 22
     &  ,CUTBIT_NFILT_TRESTMAX = 23
     &  ,CUTBIT_NFILT_TREST2   = 24
     &  ,CUTBIT_SNRMAX         = 25
     &  ,CUTBIT_SNRMAX2        = 26
     &  ,CUTBIT_NFIELD         = 27
     &  ,CUTBIT_MWEBV          = 28  ! May 2012
     &  ,CUTBIT_NSEASON_ACTIVE = 29  ! May 2019
     &  ,CUTBIT_REQEP          = 30  ! required epochs (9/17/2017)
     &  ,CUTBIT_PRIVATE        = 31  ! all private-var cuts
     &  ,CUTBIT_SIMVAR         = 32  !
     &  ,CUTBIT_OFFSET_SBFLUX  = 33  ! Mar 2012
     &  ,CUTBIT_OFFSET_SNRMAX  = 33 + MXFILT_SNRMAX
     &  ,CUTBIT_MJD_MARKER     = CUTBIT_OFFSET_SNRMAX + MXFILT_SNRMAX
     &  ,NCUTBIT_SNLC          = CUTBIT_MJD_MARKER
c SN-dependent cuts above
c MJD-dependent cuts below
     &  ,CUTBIT_PSF          = CUTBIT_MJD_MARKER + 1  ! PSF cut
     &  ,CUTBIT_ZP           = CUTBIT_MJD_MARKER + 2  ! ZP  cut (Feb 2018)
     &  ,CUTBIT_ZPERR        = CUTBIT_MJD_MARKER + 3  ! ZPERR (Feb 2020)
     &  ,CUTBIT_PHOTPROB     = CUTBIT_MJD_MARKER + 4
     &  ,CUTBIT_Trest        = CUTBIT_MJD_MARKER + 5
     &  ,CUTBIT_Tobs         = CUTBIT_MJD_MARKER + 6
     &  ,CUTBIT_MJD          = CUTBIT_MJD_MARKER + 7
     &  ,CUTBIT_TREST_TRUEFLUX2= CUTBIT_MJD_MARKER + 8
     &  ,CUTBIT_ERRTEST      = CUTBIT_MJD_MARKER + 9
     &  ,CUTBIT_SIMPULL      = CUTBIT_MJD_MARKER + 10 ! Mar 2021
c
     &  ,CUTBIT_OFFSET       = CUTBIT_SIMPULL
     &  ,NCUTBIT             = CUTBIT_OFFSET
     &      )

c Define cut-masks with 64-BIT integers

      INTEGER*8
     &   CUTMASK8_SN             ! cutmask for each SN
     &  ,CUTMASK8_MJD(MXEPOCH)   ! cutmask vs. MJD, isn
     &  ,CUTMASK8_SN_ALL         ! all bits for SN cuts
     &  ,CUTMASK8_MJD_ALL        ! all bits for MJD cuts

      BYTE MJDMASK(MXEPOCH)  ! logical for each epoch,SN

      LOGICAL
     &   LSNCUTS       ! T=> passes cuts 1 to CUTBIT_MJD_MARKER
     &  ,PASS_PRIVCUTS ! T=> pass cuts on private var in data header
     &  ,PASS_SIMCUTS  ! T=> pass cuts on SIMVAR

      INTEGER
     &   NCCID_LIST      ! size of SNCCID_LIST
     &  ,NCID_LIST       ! size of SNCID_LIST
     &  ,NCCID_IGNORE    ! size of SNCCID_IGNORE
     &  ,NCID_IGNORE     ! size of NCID_IGNORE
     &  ,CUTFLAG_SNANA   ! bits 0,1 -> LSNCUTS,LSNFITOK=T (for ntuple)
     &  ,ERRFLAG_FIT     ! error flag from fit (0=OK)

c stuff for hbook
      CHARACTER CUTVAR_NAME(NCUTBIT)*28

c define namelist cuts

      INTEGER
     &   SNTYPE_LIST(MXLISTNML)    ! I: user list of types to select
     &  ,SNTYPE_IGNORE(MXLISTNML)  ! I: types to ignore
     &  ,SNCID_LIST(MXLISTNML)     ! I: user-list of integer CIDs
     &  ,MXEVT_PROCESS             ! I: quit after processing this many
     &  ,MXEVT_CUTS                ! I: quit after Nevt passing cuts
     &  ,CCDNUM_LIST(MXLISTNML)    ! I: user-list of CCDNUMs (Dec 2017)
     &  ,SIM_TEMPLATE_INDEX_LIST(MXLISTNML)
     &  ,SNCID_IGNORE(MXLISTNML)   ! I: list of CIDs to ignore
     &  ,PHOTFLAG_MSKREJ(5)        ! I: PHOTFLAG mask-bits to reject, 1,2 => logical OR,AND
     &  ,PHOTFLAG_BITLIST_REJECT(MXBIT_PHOTFLAG)  ! I: bits to reject
     &  ,IDFIELD_LIST(MXLISTNML)   !
     &  ,NIDFIELD_LIST
     &  ,NSNTYPE_LIST           ! size of SNTYPE_LIST
     &  ,NCCDNUM_LIST           ! size of CCDNUM list
     &  ,NSIM_TEMPLATE_INDEX_LIST
     &  ,NSNTYPE_IGNORE
     &  ,NFILT_SNRMAX           ! number of CUTWIN_SNRMAX_FILT cuts
     &  ,IFILT_SNRMAX(MXFILT_SNRMAX) ! store filt index for SNRMAX cuts
     &  ,NFILT_HOST_SBFLUX      ! Nfilt to cut on HOST_SBFLUX
     &  ,IFILT_HOST_SBFLUX(MXFILT_SNRMAX)

      LOGICAL DOALL_SNTEL, DOALL_SNFIELD

      character
     &    SNFIELD_LIST(MXLISTNML)*60  ! I:  list of fields to use (or 'ALL')
     &   ,SNCCID_LIST(MXLISTNML)*(MXCHAR_CCID)   ! I: list of CIDs to process
     &   ,SNCCID_IGNORE(MXLISTNML)*(MXCHAR_CCID) ! I: list of CIDs to ignore
     &   ,SNCID_IGNORE_FILE*(MXCHAR_FILENAME)    ! I: file with CIDs to ignore
     &   ,SNCCID_IGNORE_ALL(MXIGNORE_LIST)*(MXCHAR_CCID)

c# -----------  SN-dependent cut-window  ! I: --------------------------------
      REAL
     &   snlc_cutvar(NCUTBIT_SNLC)
     &  ,snep_cutvar(CUTBIT_MJD_MARKER:NCUTBIT,MXEPOCH)
     &  ,cutwin_var(2,NCUTBIT)
     &  ,cutwin_cid(2)           ! candidate id
     &  ,cutwin_sntype(2)        !
     &  ,cutwin_redshift(2)      ! I: redshift cut
     &  ,cutwin_redshift_err(2)  ! I: cut on redshift uncertainty
     &  ,cutwin_ra(2)            ! I: cut on RA
     &  ,cutwin_dec(2)           ! I: cut on DEC
     &  ,cutwin_hostsep(2)       ! I: cut on host-SN sep, arcsec
     &  ,cutwin_sbflux_filt(2,MXFILT_SNRMAX)
     &  ,cutwin_Nepoch(2)        ! I: cut on Nepoch
     &  ,cutwin_snrmax_filt(2,MXFILT_SNRMAX)   ! filled from SNCUT_SNRMAX
     &  ,cutwin_snrmax(2)        ! I: global SNRMAX cut
     &  ,cutwin_snrmax2(2)       ! I: 2nd global SNRMAX cut (different band)
     &  ,cutwin_nfield(2)        ! I: number of fields (usually 1)
     &  ,cutwin_mwebv(2)         ! I: Galactic extinction
     &  ,cutwin_nseason_active(2)
     &  ,cutwin_cutflag_reqep(2)       ! for internal use only
     &  ,cutwin_cutflag_private(2)     ! for internal use only
     &  ,cutwin_cutflag_simvar(2)      ! for internal use only
     &  ,cutwin_nfilt_snrmax(2)  ! I: Nfilt passing global SNRMAX cut
     &  ,cutwin_nfilt_snrmax2(2) ! I: Nfilt passing 2nd-best SNRMAX
     &  ,cutwin_nfilt_trestmin(2)! I: Nfilt passing Trestmin cut
     &  ,cutwin_nfilt_trestmax(2)! I: Nfilt passing Trestmax cut
     &  ,cutwin_nfilt_trest2(2)  ! I: Nfilt passinng Trest2 cut
     &  ,cutwin_nband_thresh(2)  ! I: number of bands above $band_THRESH
     &  ,cutwin_Trestmin(2)      ! I: cut on earliest epoch, rest frame days
     &  ,cutwin_Trestmax(2)      ! I: cut on  latest epoch, rest frame day
     &  ,cutwin_TrestRange(2)    ! I: cut on Trestmax - Trestmin
     &  ,cutwin_Trest2(2)        ! I: cut on CUTWIN_NFILT_TREST2
     &  ,cutwin_Tgapmax(2)       ! I: max Trest-gap within cutwin_TREST(2)
     &  ,cutwin_T0gapmax(2)      ! I: max Trest-gap near peak
     &  ,cutwin_Tobsmin(2)       ! I: cut on min Tobs
     &  ,cutwin_Tobsmax(2)       ! I: cut on max Tobs
     &  ,cutwin_peakmjd(2)       ! I: cut on search peakMJD
c
c  Below are Epoch-dependent cuts
c# -----------  epoch-dependent cut windows  ! I: --------------------------------
     &  ,cutwin_psf(2)           ! I: PSF cut, FWHM, ARCSEC
     &  ,cutwin_zp(2)            ! I: ZEROPT cut, ADU or NPE
     &  ,cutwin_zpADU(2)         ! I: ZEROPT cut, ADU
     &  ,cutwin_zpNPE(2)         ! I: ZEROPT cut, NPE
     &  ,cutwin_ZPERR(2)         ! I: ZPERR cut
     &  ,cutwin_photprob(2)      ! I: cut on PHOTPROP (e.g., real/bogus)
     &  ,cutwin_errtest(2)       ! I: cut on ERRCALC/ERRTRUE
     &  ,cutwin_simpull(2)       ! I: cut on (F-Ftrue)/sigmaF
     &  ,cutwin_Trest_trueflux(2) ! I: Trest range requiring valid true flux
     &  ,cutwin_Trest_trueflux2(2)! I: cut on logical flag
     &  ,cutwin_Trest(2)         ! I: cut on all epochs, rest frame days
     &  ,cutwin_Tobs(2)          ! I: cut on all epochs, obs-frame days
     &  ,cutwin_MJD(2)           ! I: cut on MJD range
     &  ,CUTWIN_MJD_EXCLUDE(2)   ! I: MJD window to exclude
     &  ,CUTWIN_MJD_INCLUDE(2)   ! I: require 1 or more MJD in this window
     &  ,CUTWIN_NMJD_INCLUDE(2)         ! for internal use only
     &  ,cutwin_SEARCHEFF_MASK(2)       ! for SIM only
     &  ,cutwin_snrmin_filt(2,MXFILT_OBS) ! filled from EPCUT_SNRMIN
     &  ,cutwin_restlam(2)                ! I: cut on <LAMREST>, no cutBit
     &  ,cutwin_lamrest(2)                ! I: same as above
     &  ,cutwin_lamobs(2)                 ! I: cut on <LAMOBS>, no cutBit
     &  ,cutwin_snr_nodetect(2)    ! I: SNR cut for non-detections
c
c define character strings to specify cuts and filters
c 'SNCUT' specifies cut on each SN
c 'EPCUT' specifies selection cut on each epoch

  ! I:# --------------------------------
      CHARACTER*(MXCHAR_CUTNAME)
     &  SNCUT_SNRMAX  ! I: max SNR required in each passband
                      ! I: example: 'u 10.  g 5.0  r 5.0  i 5.0  z -10.'
c
     & ,EPCUT_SNRMIN  ! I: min SNR accepted for each epoch/filter
                      ! I: example: 'u 20000.  g -4.  r -4.  i -4.  z 20000.'
c
     & ,EPCUT_SKYSIG  ! I: max SKY noise accepted each epoch/filter
                      ! I: example: 'u 20.  g 50.  r 80.  i 120.  z 200.'
c
     & ,EPCUT_PSFSIG  ! max PSF (arcsec) accepted each epoch/filter
                      ! example: 'u 1.8  g 1.5  r 1.6  i 1.8  z 2.0'
c
     & ,SNCUT_HOST_SBFLUX ! I: require min surface brightness,
                          ! I: example 'r 1000.' -> SBFLUX > 1000

      ! I:# --------------------------------
c ----------
c systematic tests for calibration:
c 'U 01 B -0.01' => shift U & B mags of primary

     &  ,MAGOBS_SHIFT_PRIMARY  ! I: shift primary mags  (for syst test)
     &  ,MAGOBS_SHIFT_ZP       ! I: shift zero points (e.g.,AB off for SDSS)
     &  ,MAGREST_SHIFT_PRIMARY ! I: idem for rest-frame mags
     &  ,MAGREST_SHIFT_ZP      ! I: idem for rest-frame ZP
     &  ,FILTER_LAMSHIFT       ! I: e.g., 'r -2.4  i 6.2'  ! in Angstroms
c -------
c Fluxcal fudges for systematic tests (fudge photometry offsets and errors)
c Note that error is added in quadrature; ERROR<0 is subtracted in quadrature.
     &  ,FUDGE_FLUXCAL_OFFSET  ! I: shift all FLUXCAL
     &  ,FUDGE_FLUXCAL_ERROR   ! I: fudge net FLUXCAL error in each band
     &  ,FUDGE_FLUXCAL_ERRPIX  ! I: per-pixel error --> FLUXCAL error propto PSF
     &  ,FUDGE_MAG_ERROR       ! I: add stat error per band
     &  ,FUDGE_MAG_COVERR      ! I: add covariant error per band
     &  ,FUDGE_FLUXERR_SCALE   ! I: scale error in each band

      REAL
     &   MAGOBS_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGOBS_SHIFT_ZP_USER(MXFILT_ALL)      ! user ZP shift
     &  ,MAGOBS_SHIFT_ZP_FILT(MXFILT_ALL)      ! user ZP shift + system ZP
     &  ,FLUXSCALE_ZP_FILT(MXFILT_ALL)         ! corresponding flux scale
     &  ,MAGREST_SHIFT_PRIMARY_FILT(MXFILT_ALL) ! shift mag of primary ref
     &  ,MAGREST_SHIFT_ZP_USER(MXFILT_ALL)      ! shift zero points
     &  ,MAGREST_SHIFT_ZP_FILT(MXFILT_ALL)      ! shift zero points
     &  ,FILTER_LAMSHIFT_FILT(MXFILT_ALL)       ! shift filter trans
c
     &  ,MAGOBS_SHIFT_PRIMARY_PARAMS(3)       ! poly-fun of lambda;
     &  ,MAGOBS_SHIFT_ZP_PARAMS(3)            ! A0 + A1*LAM + A2*LAM^2
     &  ,FUDGE_FLUXCAL_OFFSET_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXCAL_ERRPIX_FILT(MXFILT_ALL)
     &  ,FUDGE_FLUXERR_SCALE_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_ERROR_FILT(MXFILT_ALL)
     &  ,FUDGE_MAG_COVERR_FILT(MXFILT_ALL)
     &  ,MWEBV_SCALE        ! I: scale MW extinc for syst test
     &  ,MWEBV_SHIFT        ! I: shift MW extinc
     &  ,MWEBV_FORCE        ! I: force specific MWEBV value (Feb 2020)

      REAL
     &   RV_MWCOLORLAW   ! I: RV for Galactic extinction

      INTEGER
     &   OPT_MWCOLORLAW    ! I: MW color law opt (89, 94, 99 ...)
     &  ,OPT_MWEBV         ! I: option to modify SFD maps

      LOGICAL
     &   USE_MWCOR          ! I:  T=> correct data flux for MW extinc;
                            ! I:  F=> leave data, correct fit model for MW.
      REAL
     &   REDSHIFT_FINAL_SHIFT     ! I: artificial z-shift
     &  ,HOSTGAL_PHOTOZ_SHIFT     ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,HOSTGAL_SPECZ_SHIFT      ! I: apply only when zFINAL = HOST_ZPHOT
     &  ,FLUXERRCALC_ZPTERR

      COMMON / SNCUTCOM / CUTMASK8_SN, CUTMASK8_MJD
     &   ,CUTMASK8_SN_ALL, CUTMASK8_MJD_ALL
     &   ,cutwin_var, cutvar_name
     &   ,snlc_cutvar, snep_cutvar
     &   ,cutwin_snrmin_filt, LSNCUTS
     &   ,PASS_PRIVCUTS, PASS_SIMCUTS
     &   ,CUTFLAG_SNANA , ERRFLAG_FIT
     &   ,NCCID_LIST, NCCID_IGNORE, NCID_LIST, NCID_IGNORE
     &   ,SNTYPE_LIST, SNCID_LIST, SNCCID_LIST
     &   ,SNCCID_IGNORE,SNCID_IGNORE_FILE,SNCID_IGNORE,SNCCID_IGNORE_ALL
     &   ,MXEVT_PROCESS, MXEVT_CUTS
     &   ,SNTYPE_IGNORE, CCDNUM_LIST, SIM_TEMPLATE_INDEX_LIST
     &   ,SNFIELD_LIST, IDFIELD_LIST, NIDFIELD_LIST, DOALL_SNFIELD
     &   ,NSNTYPE_LIST, NCCDNUM_LIST, NSIM_TEMPLATE_INDEX_LIST
     &   ,NSNTYPE_IGNORE, NFILT_SNRMAX, IFILT_SNRMAX
     &   ,NFILT_HOST_SBFLUX, IFILT_HOST_SBFLUX
     &   ,PHOTFLAG_MSKREJ, PHOTFLAG_BITLIST_REJECT, USE_MWCOR
     &   ,MAGOBS_SHIFT_PRIMARY, MAGOBS_SHIFT_PRIMARY_FILT
     &   ,MAGOBS_SHIFT_ZP, MAGOBS_SHIFT_ZP_FILT, FLUXSCALE_ZP_FILT
     &   ,MAGOBS_SHIFT_ZP_USER
     &   ,MAGOBS_SHIFT_PRIMARY_PARAMS, MAGOBS_SHIFT_ZP_PARAMS
     &   ,MAGREST_SHIFT_PRIMARY, MAGREST_SHIFT_PRIMARY_FILT
     &   ,MAGREST_SHIFT_ZP, MAGREST_SHIFT_ZP_FILT
     &   ,MAGREST_SHIFT_ZP_USER
     &   ,FILTER_LAMSHIFT, FILTER_LAMSHIFT_FILT
     &   ,FUDGE_FLUXCAL_OFFSET,FUDGE_FLUXCAL_ERROR,FUDGE_FLUXCAL_ERRPIX
     &   ,FUDGE_FLUXERR_SCALE
     &   ,FUDGE_FLUXCAL_OFFSET_FILT
     &   ,FUDGE_FLUXCAL_ERROR_FILT, FUDGE_FLUXCAL_ERRPIX_FILT
     &   ,FUDGE_FLUXERR_SCALE_FILT
     &   ,FUDGE_MAG_ERROR, FUDGE_MAG_ERROR_FILT
     &   ,FUDGE_MAG_COVERR, FUDGE_MAG_COVERR_FILT
     &   ,RV_MWCOLORLAW, OPT_MWCOLORLAW, OPT_MWEBV
     &   ,MWEBV_SCALE, MWEBV_SHIFT, MWEBV_FORCE
     &   ,HOSTGAL_PHOTOZ_SHIFT, HOSTGAL_SPECZ_SHIFT
     &   ,REDSHIFT_FINAL_SHIFT, FLUXERRCALC_ZPTERR
     &   ,CUTWIN_MJD_EXCLUDE, CUTWIN_MJD_INCLUDE

      COMMON / BYTEMASKCOM / MJDMASK

      EQUIVALENCE
     &    ( cutwin_var(1,cutbit_cid),       cutwin_cid )
     &   ,( cutwin_var(1,cutbit_sntype),    cutwin_sntype )
     &   ,( cutwin_var(1,cutbit_redshift),  cutwin_redshift )
     &   ,( cutwin_var(1,cutbit_redshift_err),cutwin_redshift_err )
     &   ,( cutwin_var(1,cutbit_ra),        cutwin_ra )
     &   ,( cutwin_var(1,cutbit_dec),       cutwin_dec )
     &   ,( cutwin_var(1,cutbit_hostsep),   cutwin_hostsep )
     &   ,( cutwin_var(1,cutbit_Nepoch),    cutwin_Nepoch )
     &   ,( cutwin_var(1,cutbit_psf),       cutwin_psf )
     &   ,( cutwin_var(1,cutbit_zp),        cutwin_zp  )
     &   ,( cutwin_var(1,cutbit_zperr),     cutwin_zperr  )
     &   ,( cutwin_var(1,cutbit_photprob),  cutwin_photprob  )
     &   ,( cutwin_var(1,cutbit_errtest),   cutwin_errtest   )
     &   ,( cutwin_var(1,cutbit_simpull),   cutwin_simpull   )
     &   ,( cutwin_var(1,cutbit_trest_trueflux2),cutwin_trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax), cutwin_nfilt_snrmax )
     &   ,( cutwin_var(1,cutbit_Nfilt_snrmax2),cutwin_nfilt_snrmax2 )
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmin),cutwin_nfilt_trestmin)
     &   ,( cutwin_var(1,cutbit_Nfilt_trestmax),cutwin_nfilt_trestmax)
     &   ,( cutwin_var(1,cutbit_Nfilt_trest2),  cutwin_nfilt_trest2)
     &   ,( cutwin_var(1,cutbit_Trestmin),  cutwin_Trestmin )
     &   ,( cutwin_var(1,cutbit_Trestmax),  cutwin_Trestmax )
     &   ,( cutwin_var(1,cutbit_TrestRange),cutwin_TrestRange )
     &   ,( cutwin_var(1,cutbit_Trest2),    cutwin_Trest2 )
     &   ,( cutwin_var(1,cutbit_Tgapmax),   cutwin_Tgapmax )
     &   ,( cutwin_var(1,cutbit_T0gapmax),  cutwin_T0gapmax )
     &   ,( cutwin_var(1,cutbit_Tobsmin),   cutwin_Tobsmin )
     &   ,( cutwin_var(1,cutbit_Tobsmax),   cutwin_Tobsmax )
     &   ,( cutwin_var(1,cutbit_Trest),     cutwin_Trest )
     &   ,( cutwin_var(1,cutbit_Trest_trueflux2),cutwin_Trest_trueflux2)
     &   ,( cutwin_var(1,cutbit_Tobs),      cutwin_Tobs )
     &   ,( cutwin_var(1,cutbit_MJD),       cutwin_MJD   )
     &   ,( cutwin_var(1,cutbit_peakmjd),   cutwin_peakmjd )
     &   ,( cutwin_var(1,cutbit_NMJD_INCLUDE),  cutwin_NMJD_INCLUDE )
     &   ,( cutwin_var(1,cutbit_search),        cutwin_searcheff_mask )
     &   ,( cutwin_var(1,cutbit_snrmax),        cutwin_snrmax  )
     &   ,( cutwin_var(1,cutbit_snrmax2),       cutwin_snrmax2  )
     &   ,( cutwin_var(1,cutbit_nfield),        cutwin_nfield  )
     &   ,( cutwin_var(1,cutbit_mwebv),         cutwin_mwebv  )
     &   ,( cutwin_var(1,cutbit_nseason_active),cutwin_nseason_active)
     &   ,( cutwin_var(1,cutbit_reqep),        cutwin_cutflag_reqep)
     &   ,( cutwin_var(1,cutbit_private),      cutwin_cutflag_private)
     &   ,( cutwin_var(1,cutbit_simvar),       cutwin_cutflag_simvar)
     &   ,( cutwin_var(1,cutbit_offset_sbflux+1), cutwin_sbflux_filt)
     &   ,( cutwin_var(1,cutbit_offset_snrmax+1), cutwin_snrmax_filt)
c
     &   ,( cutwin_restlam(1), cutwin_lamrest(1) )



C +CDE,SNHOSTCOM. inserted below by ypatchy. 

c Host galaxy parameters.

c logical flags for output tables
      LOGICAL
     &   EXIST_SNHOST_ANGSEP
     &  ,EXIST_SNHOST_DDLR
     &  ,EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT
     &  ,EXIST_SNHOST_LOGMASS
     &  ,EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR
     &  ,EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS
     &  ,EXIST_SNHOST_SB

      INTEGER*8  SNHOST_OBJID(MXSNHOST)    ! int id
      REAL*8    DSNHOST_OBJID(MXSNHOST)   ! for tables only
      CHARACTER VARNAME_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)*40

      REAL
     &   SNHOST_ANGSEP(MXSNHOST)      ! SN-host sep, arcsec
     &  ,SNHOST_DDLR(MXSNHOST)        ! SNSEP/DLR
     &  ,SNHOST_CONFUSION             ! HC analog from Gupta 2016
     &  ,SNHOST_ZPHOT(MXSNHOST), SNHOST_ZPHOT_ERR(MXSNHOST)
     &  ,SNHOST_ZPHOT_Q(MXSNHOST,MXZPHOT_Q)
     &  ,SNHOST_ZPHOT_PERCENTILE(MXZPHOT_Q)
     &  ,SNHOST_QZPHOT_MEAN(MXSNHOST), SNHOST_QZPHOT_STD(MXSNHOST)
     &  ,SNHOST_ZSPEC(MXSNHOST), SNHOST_ZSPEC_ERR(MXSNHOST)
     &  ,SNHOST_LOGMASS(MXSNHOST)
     &  ,SNHOST_LOGMASS_ERR(MXSNHOST)
     &  ,SNHOST_LOGSFR(MXSNHOST)
     &  ,SNHOST_LOGSFR_ERR(MXSNHOST)
     &  ,SNHOST_LOGsSFR(MXSNHOST)
     &  ,SNHOST_LOGsSFR_ERR(MXSNHOST)
     &  ,SNHOST_COLOR(MXSNHOST)
     &  ,SNHOST_COLOR_ERR(MXSNHOST)
     &  ,SNHOST_SBFLUXCAL(MXFILT_ALL)  ! surface brightness FLUXCAL /asec^2
     &  ,SNHOST_MAGOBS(MXFILT_ALL,(MXSNHOST))       ! observer-frame mags
     &  ,SNHOST_MAGOBS_ERR(MXFILT_ALL,(MXSNHOST))   ! error on above

      REAL*8
     &    SNHOST8_RA(MXSNHOST)
     &   ,SNHOST8_DEC(MXSNHOST)

c quantites which do not depend on which host
      INTEGER*4
     &    SNHOST_NMATCH   ! number of host matches, e.g., d_DLR<4
     &   ,SNHOST_NMATCH2  ! number of host matches, e.g., d_DLR<7
     &   ,SNHOST_NZPHOT_Q        ! Ma 2022: number of zphot quantiles
     &   ,SNHOST_FLAG(MXSNHOST)  ! May 21 2021: indicate problems with host

      REAL
     &   SNHOST_SBFLUXCAL_ERR(MXFILT_ALL)
     &  ,SNHOST_SBMAG(MXFILT_ALL)        ! surface brightness mag/asec^2

      COMMON / SNHOSTCOM /
     &   EXIST_SNHOST_ANGSEP, EXIST_SNHOST_DDLR, EXIST_SNHOST_CONFUSION
     &  ,EXIST_SNHOST_ZPHOT,  EXIST_SNHOST_LOGMASS, EXIST_SNHOST_LOGSFR
     &  ,EXIST_SNHOST_LOGsSFR, EXIST_SNHOST_COLOR
     &  ,EXIST_SNHOST_MAGOBS, EXIST_SNHOST_SB
c
     &  ,SNHOST_NMATCH, SNHOST_NMATCH2, SNHOST_FLAG
     &  ,SNHOST_ANGSEP, SNHOST_DDLR, SNHOST_CONFUSION
     &  ,SNHOST_ZPHOT,   SNHOST_ZPHOT_ERR
     &  ,SNHOST_ZPHOT_Q, SNHOST_ZPHOT_PERCENTILE, SNHOST_NZPHOT_Q
     &  ,SNHOST_QZPHOT_MEAN, SNHOST_QZPHOT_STD
     &  ,VARNAME_ZPHOT_Q
     &  ,SNHOST_ZSPEC,   SNHOST_ZSPEC_ERR
     &  ,SNHOST_LOGMASS, SNHOST_LOGMASS_ERR
     &  ,SNHOST_LOGSFR, SNHOST_LOGSFR_ERR
     &  ,SNHOST_LOGsSFR,    SNHOST_LOGsSFR_ERR
     &  ,SNHOST_COLOR,    SNHOST_COLOR_ERR
     &  ,SNHOST_SBFLUXCAL, SNHOST_SBFLUXCAL_ERR, SNHOST_SBMAG
     &  ,SNHOST_MAGOBS, SNHOST_MAGOBS_ERR

      COMMON / SNHOSTCOM8 /
     &   SNHOST_OBJID, DSNHOST_OBJID, SNHOST8_RA, SNHOST8_DEC

cc +CDE,PARSECOM.

C +CDE,SNSIMCOM. inserted below by ypatchy. 

c simulation parameters (if FAKE=2)

      REAL*8  SIM8_RA, SIM8_DECL

      REAL
     &   SIM_REDSHIFT_HELIO
     &  ,SIM_REDSHIFT_CMB
     &  ,SIM_REDSHIFT_HOST
     &  ,SIM_VPEC
     &  ,SIM_DLMAG
     &  ,SIM_LENSDMU
     &  ,SIM_MWEBV
     &  ,SIM_MWRV
c
     &  ,SIM_WGT_POPULATION     ! Dec 2023: for biasCor sims only
     &  ,SIM_SALT2x0
     &  ,SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW
     &  ,SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_EXPOSURE_TIME(MXFILT_OBS)  ! relative exposure time
     &  ,SIM_PEAKMAG(MXFILT_OBS)
     &  ,SIM_EPMAGOBS(MXEPOCH)      ! true epoch mag at each filter/epoch
     &  ,SIM_EPFLUXCAL(MXEPOCH)     ! true fluxcal at each filter/epoch
     &  ,SIM_EPSNRMON(MXEPOCH)      ! optional SNR at MAGMONITOR
     &  ,SIM_EPMAGREST(MXEPOCH)     ! true rest-frame mag
     &  ,SIM_EPFLUXCAL_HOSTERR(MXEPOCH) ! true error from host noise
     &  ,SIM_EPCHI2FLUX(MXEPOCH)    ! data-sim chi2 per epoch
     &  ,SIM_EPPULL(MXEPOCH)        ! pull per epoch (F-Ftrue)/sig)
     &  ,SIM_EPdRA(MXEPOCH)
     &  ,SIM_EPdDEC(MXEPOCH)
     &  ,SIM_EPdMAG(MXEPOCH)
c
     &  ,SIMSED_PARVAL(MXPAR_SIMSED)
     &  ,PySEDMODEL_PARVAL(MXPAR_SIMSED)    ! Dec 10 2018
     &  ,LCLIB_PARVAL(MXPAR_LCLIB)
     &  ,SIM_HOSTLIB_PARVAL(MXPAR_SIMSED) ! HOSTLIB params
     &  ,SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM             ! usually this is gamma or gamma/2
     &  ,SIM_TEMPLATEMAG(MXFILT_ALL)  ! image-sub template, not LCLIB template
     &  ,SIM_LCWIDTH(MXFILT_ALL)      ! computed from SIM_EPFLUXCAL
c
     &  ,SIM_MODELGRID_TOBS(MXEP_MODELGRID)    ! for SNANA+SIM_MAGOBS table
     &  ,SIM_MODELGRID_MAGOBS(MXEP_MODELGRID,MXFILT_OBS/2) ! idem

      REAL SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT ! read from README

      INTEGER
     &   SIM_MODEL_INDEX      ! model index (MLCS,SALT2,NON1a ...)
     &  ,SIM_GENTYPE          ! generated SNTYPE; SIM_TYPE_INDEX
     &  ,SIM_TEMPLATE_INDEX   ! template index for NON1ASED, SIMSED, LCLIB ...
     &  ,SIM_SEARCHEFF_MASK   ! bits 1,2 => found by software,humans
     &  ,SIM_LIBID            ! LIBID for each event
     &  ,SIM_NGEN_LIBID       ! NGEN for this LIBID (usually 1)
     &  ,SIM_NOBS_UNDEFINED   ! NOBS where model is undefined
     &  ,SIM_NSUBSAMPLE_MARK  ! Number of marked sub-samples
     &  ,SIM_SUBSAMPLE_INDEX  ! sub-sample index
     &  ,SIM_REDSHIFT_FLAG    ! points to source of redshift
     &  ,SIMOPT_MWCOLORLAW    ! option for MW color law
     &  ,SIMOPT_MWEBV         ! option to modify MWEBV_SFD map
     &  ,NPAR_SIMSED
     &  ,NPAR_PySEDMODEL      ! BYOSED, SNEMO ...
     &  ,NPAR_LCLIB
     &  ,NPAR_SIM_HOSTLIB
     &  ,SIM_EPFILTREST(MXEPOCH)
     &  ,SIMLIB_MSKOPT        ! SIMLIB option mask (Dec 2015)
     &  ,SIM_BIASCOR_MASK     ! non-zero -> it's a biasCor sim
     &  ,NEP_SIM_MODELGRID
     &  ,NEP_SIM_MAGOBS          ! number of sim epochs with MAGOBS < 99


      INTEGER*8  SIM_HOSTLIB_GALID
      REAL*8    DSIM_HOSTLIB_GALID  ! for table only

      CHARACTER
     &   SIMNAME_MODEL*(MXCHAR_MODELNAME)     ! SALT2, mlcs2k2, NON1A, etc ...
     &  ,SIMNAME_TYPE*12      ! Ia, Ib, II, IIN, etc ...
     &  ,SIMNAME_SHAPEPAR*40  ! DELTA, x1, stretch ...
     &  ,SIMNAME_SHAPELAW*40  ! alpha ...
     &  ,SIMNAME_COLORPAR*40  ! AV, c ...
     &  ,SIMNAME_COLORLAW*40  ! RV,  beta ...
     &  ,SIMLIB_FILENAME*200  ! SIMLIB file used to generate sim
     &  ,SIMSED_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,SIMSED_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,PySEDMODEL_NAME*20              ! e.g., 'BYOSED' , 'SNEMO'
     &  ,PySEDMODEL_KEYWORD(MXPAR_SIMSED)*80 ! full keyname in header
     &  ,PySEDMODEL_PARNAME(MXPAR_SIMSED)*20 ! parname for fitres and ntuple
     &  ,LCLIB_KEYWORD(MXPAR_LCLIB)*80 ! full keyname in header
     &  ,LCLIB_PARNAME(MXPAR_LCLIB)*20 ! parname for fitres and ntuple
     &  ,SIM_HOSTLIB_KEYWORD(MXPAR_SIMSED)*60 ! full keyname
     &  ,SIM_HOSTLIB_PARNAME(MXPAR_SIMSED)*60 ! parname
     &  ,SIMNAME_SNRMON*40

      LOGICAL
     &  LSIM_TRUE_SNIa   ! true SNIa (SALT3 or BAYES or MLCS ...)
     & ,LSIM_TRUE_NONIa  ! true NONIa (SNCC, AGN, TDE ...)

      COMMON / SNSIMCOM / SIMNAME_MODEL, SIM_MODEL_INDEX
     &  ,SIM_REDSHIFT_HELIO, SIM_REDSHIFT_CMB, SIM_REDSHIFT_HOST
     &  ,SIM_REDSHIFT_FLAG
     &  ,SIM_VPEC, SIM_DLMAG, SIM_LENSDMU
     &  ,SIM_WGT_POPULATION, SIM_SALT2x0, SIM_SALT2mb
     &  ,SIM_COLORPAR, SIM_COLORLAW, SIM_AV, SIM_RV
     &  ,SIM_SHAPEPAR, SIM_SHAPELAW, SIM_PEAKMJD, SIM_MJD_EXPLODE
     &  ,SIM_MWEBV,SIM_MWRV
     &  ,SIM_EXPOSURE_TIME, SIM_TEMPLATE_INDEX, SIM_TEMPLATEMAG
     &  ,SIM_GENTYPE, SIMNAME_TYPE, SIM_LCWIDTH
     &  ,SIM_SEARCHEFF_MASK, SIM_LIBID, SIM_NGEN_LIBID
     &  ,SIM_NOBS_UNDEFINED, SIM_NSUBSAMPLE_MARK, SIM_SUBSAMPLE_INDEX
     &  ,SIM_PEAKMAG, SIM_EPMAGOBS, SIM_EPFLUXCAL, NEP_SIM_MAGOBS
     &  ,SIM_EPSNRMON, SIM_EPCHI2FLUX, SIM_EPPULL, SIM_EPFLUXCAL_HOSTERR
     &  ,SIM_EPdRA, SIM_EPdDEC, SIM_EPdMAG
     &  ,SIMNAME_SHAPEPAR,  SIMNAME_SHAPELAW
     &  ,SIMNAME_COLORPAR,  SIMNAME_COLORLAW, SIMNAME_SNRMON
     &  ,SIMLIB_FILENAME, SIMLIB_MSKOPT, SIM_BIASCOR_MASK
     &  ,SIMOPT_MWCOLORLAW, SIMOPT_MWEBV
     &  ,SIM_EPFILTREST, SIM_EPMAGREST,  SIM_MAGSMEAR_COH
     &  ,SIM_SALT2gammaDM
     &  ,NEP_SIM_MODELGRID, SIM_MODELGRID_TOBS, SIM_MODELGRID_MAGOBS
     &  ,SIM_OM, SIM_OL, SIM_w0, SIM_wa, SIM_MUSHIFT
     &  ,LSIM_TRUE_SNIa, LSIM_TRUE_NONIa

      COMMON / SIMSEDCOM /
     &  NPAR_SIMSED, SIMSED_PARVAL, SIMSED_PARNAME, SIMSED_KEYWORD

      COMMON / PySEDCOM /
     &   PySEDMODEL_NAME, NPAR_PySEDMODEL, PySEDMODEL_PARVAL,
     &   PySEDMODEL_PARNAME, PySEDMODEL_KEYWORD

      COMMON / LCLIBCOM /
     &   NPAR_LCLIB, LCLIB_PARVAL, LCLIB_KEYWORD, LCLIB_PARNAME

      COMMON / SIMHOSTCOM /
     &    NPAR_SIM_HOSTLIB, SIM_HOSTLIB_PARVAL
     &   ,SIM_HOSTLIB_PARNAME, SIM_HOSTLIB_KEYWORD

      COMMON / SNSIMCOM8 /
     &   SIM8_RA, SIM8_DECL, SIM_HOSTLIB_GALID, DSIM_HOSTLIB_GALID



C +CDE,SNFITPAR. inserted below by ypatchy. 

      INTEGER
     &   IPAR_ITER
     &  ,IPAR_ISN
     &  ,IPAR_PEAKMJD
     &  ,IPAR_SHAPE
     &  ,IPAR_SHAPE2
     &  ,IPAR_AV
     &  ,IPAR_RV, IPAR_AVRV
     &  ,IPAR_DLMAG, IPAR_ZPHOT
     &  ,IPAR_X0, IPAR_COLOR  ! for SALT2
     &  ,IPAR_MB              ! for SALT2
     &  ,IPAR_MAX
     &  ,IPAR_SPARE
c  Define Error flags
c  _FIT -> fixed redshift; _ZFIT -> photoz fit
     &  ,ERRFLAG_FITPREP_NOFILTERS
     &  ,ERRFLAG_FITPREP_NOEPOCHS
     &  ,ERRFLAG_FITPREP_NEPOCH
     &  ,ERRFLAG_FIT_BADCOV
     &  ,ERRFLAG_FIT_CRAZYERR
     &  ,ERRFLAG_FIT_MARGINALIZE
     &  ,ERRFLAG_FIT_CUTS
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS
     &  ,ERRFLAG_ZFIT_RANGE
     &  ,ERRFLAG_REPEAT_ITER
     &  ,ERRFLAG_REPEAT_MINOS
c
     &  ,OPT_FITANA_STORE_VAL
     &  ,OPT_FITANA_STORE_ERR

      PARAMETER (
     &   IPAR_ITER            =  1  ! iteration: 1,2 ... NFIT_ITERATION
     &  ,IPAR_ISN             =  2
     &  ,IPAR_PEAKMJD         =  3  ! MJD at peak
     &  ,IPAR_SHAPE           =  4  ! stretch or delta, or dm15 ...
     &  ,IPAR_SHAPE2          =  5  ! 2nd shape-param
     &  ,IPAR_AV              =  6
     &  ,IPAR_COLOR           =  IPAR_AV     ! for SALT2
     &  ,IPAR_RV              =  7           ! MLCS-RV
     &  ,IPAR_MB              =  IPAR_RV     ! for SALT2
     &  ,IPAR_AVRV            =  IPAR_RV     ! AV/RV
     &  ,IPAR_DLMAG           =  8           ! distance modulus
     &  ,IPAR_X0              =  IPAR_DLMAG  ! for SALT2
     &  ,IPAR_ZPHOT           =  9           ! photoZ
     &  ,IPAR_MAX             =  9  ! max number of fit params
     &  ,IPAR_SPARE           =  IPAR_MAX + 1
c
     &  ,ERRFLAG_FITPREP_NOFILTERS  =  1  ! no valid filters
     &  ,ERRFLAG_FITPREP_NOEPOCHS   =  2  ! no epochs in FITINI_COV
     &  ,ERRFLAG_FITPREP_NEPOCH     =  3  ! too few epochs
     &  ,ERRFLAG_FIT_BADCOV         =  9  ! MNSTAT returns ISTAT<3
     &  ,ERRFLAG_FIT_CRAZYERR       = 10  ! insane error detected
     &  ,ERRFLAG_FIT_MARGINALIZE    = 11  ! could not marginalize
     &  ,ERRFLAG_FIT_CUTS           = 12  ! failed 1 or more cuts
     &  ,ERRFLAG_ZFIT_DROPFILTCUTS  = 13  ! fail Zphot-cuts after drop filter
     &  ,ERRFLAG_ZFIT_RANGE         = 14  ! Zphot outside valid range
     &  ,ERRFLAG_REPEAT_ITER        = -1  ! repeat fit iteration
     &  ,ERRFLAG_REPEAT_MINOS       = -2  ! repeat entire it with MINOS
c
     &  ,OPT_FITANA_STORE_VAL = 1
     &  ,OPT_FITANA_STORE_ERR = 2
     &    )


c  OPT_PHOTOZ mask options for redshift prior (Jun 3 2022)
      INTEGER
     &   BIT_PHOTOZ_GAUSS  ! use <zPhot> and RMS in Gauss approx
     &  ,BIT_BESTZ_GAUSS   ! idem, but with best redshift (e.g., zSpec)
     &  ,BIT_PHOTOZ_QUANTILES ! use photo-z quantiles for prior
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN ! replace default cubic with Steffen
     &  ,BIT_PHOTOZ_CHEAT  ! use correct redshift and filters


      PARAMETER (
     &   BIT_PHOTOZ_GAUSS            = 0  ! OPT_PHOTOZ += 1
     &  ,BIT_BESTZ_GAUSS             = 1  ! OPT_PHOTOZ += 2
     &  ,BIT_PHOTOZ_QUANTILES        = 2  ! OPT_PHOTOZ += 4
     &  ,BIT_PHOTOZ_QUANTILES_STEFFEN = 3  ! OPT_PHOTOZ += 8 ! note: set OPT_PHOTOZ = 12 for this option
     &  ,BIT_PHOTOZ_CHEAT            = 4  ! OPT_PHOTOZ += 16
     &    )

      CHARACTER METHOD_SPLINE_QUANTILES*20
      COMMON/PHOTOZ_COM/METHOD_SPLINE_QUANTILES


      INTEGER hid, NBAV, NBZ, iav, ilum, iz, ISN, NDIM, NBIN(2)
      REAL*8
     &   XVAL(10), EFF, AV, DELTA, Z, WGT
     &  ,AVMIN, AVMAX, AVBIN
     &  ,ZMIN,  ZMAX,  ZBIN, MWEBV
     &  ,DMIN(2), DMAX(2), DVAL(2)

      CHARACTER chis*80

c function
      REAL*8  SNLC_FIT_SIMEFF

C ------------- BEGIN ----------

C hard wire redshift and AV bins

      NDIM  = 2  ! 2D plots
      WGT   = 1.0

      AVMIN = -0.1
      AVMAX =  2.0
      AVBIN =  0.02
      NBAV   = (AVMAX - AVMIN + 1.0E-5)/AVBIN

      ZMIN = 0.05
      ZMAX = 0.95
      ZBIN = 0.10
      NBZ   = (ZMAX - ZMIN + 1.0E-5)/ZBIN

      NBIN(1) = NBZ
      NBIN(2) = NBAV
      DMIN(1) = ZMIN
      DMIN(2) = AVMIN
      DMAX(1) = ZMAX
      DMAX(2) = AVMAX

c set artificial ISN index to and set MWEBV=0 temporarily
      ISN = 1
      MWEBV = SNLC_MWEBV
      SNLC_MWEBV = 0.0


      DO 100 ilum = 1, 5  ! loop over DELTA values

        DELTA = -0.5 + float(ilum-1)*.2
        XVAL(IPAR_SHAPE)  = DELTA

c book EFF vs. AV & Z for this DELTA value.
          write(chis,20) DELTA
20        format('SIMEFF vs. AV and z,  DELTA=',F5.2)
          chis = chis(1:40) // char(0)
          hid = 18000 + ilum
          CALL SNHIST_INIT(NDIM, HID, CHIS, NBIN,DMIN,DMAX, 80 )

        DO 201 iz  = 1, NBZ
          Z  = ZMIN + ZBIN * (FLOAT(iz)-0.5)
          XVAL(IPAR_zPHOT)   = Z
        DO 202 iav = 1, 210
          AV = AVMIN + AVBIN * (FLOAT(iav)-0.5)
          XVAL(IPAR_AV)  = AV
          EFF  = SNLC_FIT_SIMEFF(ISN,XVAL)

          DVAL(1) = Z
          DVAL(2) = AV
          CALL SNHIST_FILL(NDIM, HID, DVAL, EFF )

202     CONTINUE

201     CONTINUE

100   CONTINUE

c restore MWEBV
      SNLC_MWEBV = MWEBV

      RETURN
      END
CDECK  ID>,  USRINI. 
      SUBROUTINE USRINI(IERR)
c
c User init-routine called once aftet SN are read in,
c but before they are analyzed.
c -------------------------------------
      IMPLICIT NONE
      INTEGER IERR ! (O) 0 => OK
c local var
      INTEGER LL
C ------------------- BEGIN ---------------------
      IERR = 0
      RETURN
      END

C ===========================================
CDECK  ID>,  USRINI2. 
      SUBROUTINE USRINI2(IERR)
      IMPLICIT NONE
      INTEGER IERR
      IERR = 0
      RETURN
      END

C ===========================================
CDECK  ID>,  USRCUTS. 
      SUBROUTINE USRCUTS(IERR)
      IMPLICIT NONE
c declare subroutine args
      INTEGER IERR ! (O) 0 => OK
C ------------------- BEGIN ---------------------
      IERR = 0
      RETURN
      END

C ===========================================
CDECK  ID>,  USRANA. 
      SUBROUTINE USRANA(IERR)
c
c User analysis routine for each Supernova
c See SNLC_XXX varibales in
c      $SNANA_DIR/src/snana.car
c
c -------------------------------------
      IMPLICIT NONE
c +CDE,SNDATCOM.
c declare subroutine args
      INTEGER IERR ! (O) 0 => OK
C ------------------- BEGIN ---------------------
      IERR = 0
      RETURN
      END

C ===========================================
CDECK  ID>,  USREND. 
      SUBROUTINE USREND(IERR)
c
c User end-routine after all analysis/fits are done.
c [close files, summarize statistics, global analysis, etc ...]
c -------------------------------------
      IMPLICIT NONE
      INTEGER IERR ! (O) 0 => OK
c local var
      INTEGER LL
C ------------------- BEGIN ---------------------
      IERR = 0
      RETURN
      END


